在perl正则表达式中打印匹配的单词

时间:2017-02-24 02:56:54

标签: regex perl

我需要从perl中的存储行打印所有匹配的字符串。我看过各种各样的帖子 Print the matched string using perl Perl Regex - Print the matched value

我尝试首先尝试打印第一个单词。但是我收到了构建错误

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"; }

0 个答案:

没有答案