On Fri, Jan 21, 2022 at 6:58 PM Ed Avis <ed.avis@pgim.com> wrote: > On the subject of passing aliases to subroutines, I will note there is a > longstanding wart with passing regexp capture variables. > > our $CONFIG = 'logging level 5'; > > sub foo { > if ($CONFIG =~ /logging level (\d+)/) { say "set logging to $1" } > say "string is $_[0]"; > } > > $_ = 'hello'; > /(.+)/ or die; > foo($1); > > The contents of @_ get unexpectedly changed by what looks like a read-only > regexp operation on some other variable. This gotcha does lead to bugs in > real code. I think it would be better for perl to take a copy of $1, etc, > when passing them to subroutines, rather than passing an alias. After all, > that's the behaviour we expect for other magic variables like $_. > It actually isn't. Passing $_ around can lead to similar issues due to its superglobal nature. The only protection is the implicit localization done by foreach/map/grep when using it, most commonly bugs arise from using while-readline which clobbers $_ and does not localize it, as with regular assignment. -DanThread Previous | Thread Next