in reply to why is $1 cleared at end of an inline sub?
As documented in Variables related to regular expressions and lower down for $1:
These variables are read-only and dynamically-scoped.
The dynamic scoping (see also Temporary Values via local()) makes sense because it means code like this still works:
sub do_something_else { my $foo = "quzbaz"; $foo =~ /([aeiou]+)/ and print ">$1\n"; # prints ">u" } my $bar = "foobar"; if ( $bar =~ /([aeiou]+)/ ) { do_something_else(); print "$1\n"; # still prints "oo", not "u" }
As a general rule, regular expression variables that you want to keep for later use should be copied into other variables ASAP, and only if the match was successful.
Update: Better link instead of local
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: why is $1 cleared at end of an inline sub?
by perl-diddler (Chaplain) on Sep 17, 2021 at 20:27 UTC | |
by haukex (Archbishop) on Sep 17, 2021 at 22:41 UTC | |
by LanX (Saint) on Sep 17, 2021 at 21:34 UTC | |
by choroba (Cardinal) on Sep 17, 2021 at 20:52 UTC | |
by LanX (Saint) on Sep 17, 2021 at 23:08 UTC |
In Section
Seekers of Perl Wisdom