develooper Front page | perl.perl5.porters | Postings from January 2022

Re: Subroutine arguments as aliases (was: Benchmarking a 'no-snails'world (was: Re: PSC #049 2022-01-07))

Thread Previous | Thread Next
From:
Dan Book
Date:
January 22, 2022 00:04
Subject:
Re: Subroutine arguments as aliases (was: Benchmarking a 'no-snails'world (was: Re: PSC #049 2022-01-07))
Message ID:
CABMkAVUaqBsatUQt274L4xu4QWfuATaMD01UrMrhH_ueahqX4A@mail.gmail.com
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.

-Dan

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About