explorer has asked for the wisdom of the Perl Monks concerning the following question:
I have this problem: to capture two strings into an URL, but if the first string have the 'video' string, I need that $1 and $2 return '' (o undefined).
Output:foreach my $url ( '<a href="/story/43480/">The Bottled Water Lie</a>', '<a href="/story/video/43480/">The Bottled Water Lie</a>', ) { print " $url\n"; if ( $url =~ m{href="(.+)">(.+)</a>} ) { print "O1: $1\n"; print "O2: $2\n"; if ( $1 !~ /video/ ) { print "Y1: $1\n"; print "Y2: $2\n"; } else { print "N1: $1\n"; print "N2: $2\n"; } print "F1: $1\n"; print "F2: $2\n"; } print "L1: $1\n"; print "L2: $2\n"; }
Ok. This work. The second $url don't show nothing... but... into the else part (N1 & N2 lines) shown that match variables are reset to undef. And the F1 & F2 lines show undefined vars also.<a href="/story/43480/">The Bottled Water Lie</a> O1: /story/43480/ O2: The Bottled Water Lie Y1: /story/43480/ Y2: The Bottled Water Lie F1: /story/43480/ F2: The Bottled Water Lie L1: /story/43480/ L2: The Bottled Water Lie <a href="/story/video/43480/">The Bottled Water Lie</a> O1: /story/video/43480/ O2: The Bottled Water Lie N1: N2: F1: F2: L1: /story/video/43480/ L2: The Bottled Water Lie
perlre say:
The numbered match variables ($1, $2, $3, etc.) and the related punctuation set ($+ , $& , $` , $' , and $^N ) are all dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See "Compound Statements" in perlsyn.)But the second 'if' reset the match variables in a failed test.NOTE: failed matches in Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match.
So... I need a very deep explanation of this mystery, please.
Anyway, I reduced the problem to
but I don't know how it is working, also :-($url =~ m{href="(.+)">(.+)</a>} and $1 !~ /video/; print "$1 $2 \n";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Extraneous behaviour of match variables
by ikegami (Patriarch) on Nov 03, 2006 at 03:49 UTC | |
by explorer (Chaplain) on Nov 03, 2006 at 13:34 UTC | |
by Fletch (Bishop) on Nov 03, 2006 at 14:30 UTC | |
by ikegami (Patriarch) on Nov 03, 2006 at 15:41 UTC |
Back to
Seekers of Perl Wisdom