in reply to Modifying value of $1 clobbers $2, $3 etc?

Liz already gave you the reason why it doesn't do what you want: because the s/// updates these variables.

What she didn't tell you, is that you can fix this, by adding a block level, putting the s/// in its own block.

#! perl -w 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 }
which yields:
<Learning Perl ><Schwartz, Randal L ><xxxx>
Ain't that magic.

It's all hidden in that piece of documentation that you quoted:

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.
and here, because the s/// has its own block, the $1, $2, $3 also have their own limited scope. Outside that block, the outer values are restored. It is indeed as if there's an implicit local applied to them. So your values, the ones you want to show, got restored to the values your pattern match yielded, ready for you to print them.

Replies are listed 'Best First'.
Re: Re: Modifying value of $1 clobbers $2, $3 etc?
by perbu (Sexton) on Oct 12, 2003 at 13:58 UTC
    Why not split the sting right into properly named variables? IMHO it's more understandeble. Besides, it's more compact - which is generally a good thing.
    #! perl -w use strict; use warnings; my $str = "Title: Learning Perl Author: Schwartz, Randal L. ISBN: xx +xx"; if ( my ($title, $author, $isbn) = $str =~ /^Title: (.*)\s+Author: (.*)\s+ISBN: (.*)/ ) { $author =~ s/\.//g; # Remove full stops (periods) print "<$title><$author><$isbn>"; # Line 8 }
Re: Re: Modifying value of $1 clobbers $2, $3 etc?
by liz (Monsignor) on Oct 12, 2003 at 13:24 UTC
    The reason I didn't tell this, was that I was living under the wrong assumption that the scope trick didn't work with the regex variables $1 etc. ;-)

    Again, a new thing learned/corrected on Perl Monks! Thanks bart!

    Liz