Not_a_Number has asked for the wisdom of the Perl Monks concerning the following question:
Consider the following snippet:
use strict; use warnings; my $str = "Title: Learning Perl Author: Schwartz, Randal L. ISBN: xx +xx"; if ( $str =~ /^Title: (.*)\s+Author: (.*)\s+ISBN: (.*)/ ) { # print "<$1><$2><$3>\n"; my $author = $2; $author =~ s/\.//g; # Remove full stops (periods) print "<$1><$author><$3>"; # Line 8 }
The output I get is:
Use of uninitialized value <snip> line 8. Use of uninitialized value <snip> line 8. <><Schwartz, Randal L ><>
What has happened to $1 and $3?
According to perldoc perlre:
The scope of $<digit> extends to the end of the enclosing BLOCK or eval string, or to the next successful pattern match, whichever comes first.
which I understand to mean that $1 and $3 should still be in scope.
Interestingly, if the substitution fails (ie here if there is no "." in $author to substitute), line 8 works as expected...
Version: AS Perl 5.61 Win ME and XXXX
Please note: I'm not looking for alternative or "better" ways of parsing such a string; I can think of several. My question is only why this way doesn't work.TIA
dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Modifying value of $1 clobbers $2, $3 etc?
by liz (Monsignor) on Oct 12, 2003 at 10:52 UTC | |
by Roger (Parson) on Oct 12, 2003 at 11:15 UTC | |
by Not_a_Number (Prior) on Oct 12, 2003 at 12:32 UTC | |
|
Re: Modifying value of $1 clobbers $2, $3 etc?
by bart (Canon) on Oct 12, 2003 at 11:42 UTC | |
by perbu (Sexton) on Oct 12, 2003 at 13:58 UTC | |
by liz (Monsignor) on Oct 12, 2003 at 13:24 UTC | |
|
Re: Modifying value of $1 clobbers $2, $3 etc?
by jonadab (Parson) on Oct 12, 2003 at 11:37 UTC | |
|
Re: Modifying value of $1 clobbers $2, $3 etc?
by robartes (Priest) on Oct 12, 2003 at 10:55 UTC |