我需要打印perl中存儲的所有匹配的字符串。我看到的這個 Print the matched string using perl Perl Regex - Print the matched value在perl中打印匹配的字
各個崗位和我嘗試先嚐試打印的第一個字。但我得到一個生成錯誤
Use of uninitialized value $1 in concatenation (.) or string at rg.pl line 10.
我已經試過拆分和數組,它的工作原理,但打印$ 1時,它會引發錯誤。
我的代碼是在這裏
#!/usr/bin/perl/
use warnings;
use strict;
#my $line = "At a far distance near the bar, was a parked car. Star were shining in the night. The boy in the car had scar and he was at war with his enemy. \n";
my $line = "At a far distance near the bar, was a parked car. \n";
if($line =~ /[a-z]ar/gi)
{ print "$1 \n"; }
$_ = $line;
我想我對這段代碼的輸出是
far
,並隨後打印包含AR的所有單詞,
far
near
bar
parked
car
我甚至嘗試改變我的代碼,如下,但沒有奏效,同樣的錯誤
if($line =~ /[a-z]ar/gi) {
my $match = $1;
print "$match \n"; }
您能否多給點解釋一下,這兩種工作方式有什麼不同? if($ line =〜/([a-z] ar)i /){print「$ 1 \ n」} if($ line =〜/ [a-z] ar/gi) {print「$ 1 \ n」; } –
一個是全局匹配('g'),另一個不是。 –
不,我的意思是捕捉部分你最近怎麼樣? –