Perl: Empty $1 regex value when matching?

2019-02-27 18:56发布

问题:

Readers,

I have the following regex problem:

code

 #!/usr/bin/perl -w
use 5.010;
use warnings;

my $filename = 'input.txt';
open my $FILE, "<", $filename or die $!;

while (my $row = <$FILE>)
{                   # take one input line at a time
    chomp $row;
    if ($row =~ /\b\w*a\b/)
    {
       print "Matched: |$`<$&>$'|\n";  # the special match vars
       print "\$1 contains '$1' \n";
    }
    else
    {
       #print "No match: |$row|\n";
    }
}

input.txt

I like wilma. 
this line does not match

output

Matched: |I like <wilma>|
Use of uninitialized value $1 in concatenation (.) or string at ./derp.pl line 14, <$FILE> line 22.
$1 contains ''

I am totally confused. If it is matching and I am checking things in a conditional. Why am I getting an empty result for $1? This isn't supposed to be happening. What am I doing wrong? How can I get 'wilma' to be in $1?

I looked here but this didn't help because I am getting a "match".

回答1:

You don't have any parentheses in your regex. No parentheses, no $1.

I'm guessing you want the "word" value that ends in -a, so that would be /\b(\w*a)\b/.

Alternatively, since your whole regex only matches the bit you want, you can just use $& instead of $1, like you did in your debug output.

Another example:

my $row = 'I like wilma.';
$row =~ /\b(\w+)\b\s*\b(\w+)\b\s*(\w+)\b/;
print join "\n", "\$&='$&'", "\$1='$1'", "\$2='$2'", "\$3='$3'\n";

The above code produces this output:

$&='I like wilma'
$1='I'
$2='like'
$3='wilma'