문제

I found it strange that backreferences ($1,$2,$3) were not working in my original code, so I ran this example from the web:

#!/usr/bin/perl
# matchtest2.plx
use warnings;
use strict;
$_ = '1: A silly sentence (495,a) *BUT* one which will be useful. silly (3)';
my $pattern = "silly";
if (/$pattern/) {
    print "The text matches the pattern '$pattern'.\n";
    print "\$1 is '$1'\n" if defined $1;
    print "\$2 is '$2'\n" if defined $2;
    print "\$3 is '$3'\n" if defined $3;
    print "\$4 is '$4'\n" if defined $4;
    print "\$5 is '$5'\n" if defined $5;
}
else {
     print "'$pattern' was not found.\n";
}

Which only gave me:

The text matches the pattern 'silly'.

Why are the backreferences still undefined after the pattern was found? I am using Wubi (Ubuntu 12.04 64-bit) and my perl version is 5.14.2. Thank you in advance for your help.

도움이 되었습니까?

해결책 2

This is expected behaviour! It is obvious that you pattern will match, so it is no suprise that the corresponding if-block is executed.

The term “backreferences” for $1, $2, ... may be slightly suboptimal, let's call them “capture groups”.

In a regex, you can enclose parts of the pattern with parens to be remembered later:

/(silly)/

This pattern has one group. The contents of this group will be stored in $1 if it matches.

All capture group variables for groups that don't exists in the pattern or were not populated are set to undef on an otherwise successfull match, so for above pattern $2, $3, ... would all be undef.

다른 팁

You are not capturing any strings: No parentheses in your pattern. If you had done:

my $pattern = "(silly)";

You would have gotten something in $1.

In case you do not know, $1 is the text captured in the first parentheses, $2 the second parentheses, and so on.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top