3

情况1:

year$ = ($whole =~ /\d{4}/);
print ("The year is $year for now!";)

输出: 年份是 现在年份是 1!

案例二:

$whole="The year is 2020 for now!";
$whole =~ /\d{4}/;
$year =  ($whole);
print ("The year is $year for now!";)

输出: 现在是 2020 年!目前!

有没有办法让 $year 变量只在 2020 年发生?

4

3 回答 3

1

$year使用括号捕获匹配,并一步将其分配给所有:

use strict;
use warnings;

my $whole = "The year is 2020 for now!";
my ( $year ) =  $whole =~ /(\d{4})/;
print "The year is $year for now!\n";
# Prints:
# The year is 2020 for now!

请注意,我将此添加到您的代码中,以启用捕获错误、拼写错误、不安全的结构等,从而阻止您显示的代码运行:

use strict;
use warnings;
于 2020-09-22T05:41:16.440 回答
0

这是另一种捕获它的方法。这有点类似于@PYPL 的解决方案

use strict;
use warnings;

my $whole = "The year is 2020 for now!";

my $year;
($year = $1) if($whole =~ /(\d{4})/);

print $year."\n";
print "The year is $year for now!";

输出:

2020
The year is 2020 for now!
于 2020-09-22T06:00:35.523 回答
0

您必须将其捕获到一个组中

$whole="The year is 2020 for now!";
$whole =~ m/(\d{4})/;
$year =  $1;
print ("The year is $year for now!");
于 2020-09-22T05:21:18.467 回答