Perl Regex 变量替换打印 1 而不是所需的提取

Perl Regex Variable Replacement printing 1 instead of desired extraction

案例一:

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?

你得抓拍成团

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

使用括号捕获匹配项,并一步将其分配给 $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;

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

use strict;
use warnings;

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

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

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

输出:

2020
The year is 2020 for now!