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

Re: Can't localize lexical variable $x at ...

Thread Previous | Thread Next
From:
demerphq
Date:
January 25, 2022 15:58
Subject:
Re: Can't localize lexical variable $x at ...
Message ID:
CANgJU+WoWyyfa0gJpWiYFt2zko=UBKTkPzcqZd90D-0hJQuY2Q@mail.gmail.com
On Tue, 25 Jan 2022, 23:43 , <hv@crypt.org> wrote:

> yb@rslinux.fun wrote:
> :On Tue, Jan 25, 2022 at 01:20:17PM +0000, hv@crypt.org wrote:
> :> I think of local() as "temporarily replace the value at this lvalue
> :> with a new value, restore it at the end of the current lexical scope".
> :> This is hugely useful in many situations that would otherwise require
> :> more and slower code with much more opportunity for error.
> :
> :Out of curiosity, is there any reason not to simply shadow it: my $x =
> ...?
>
> In this case, it's an inline recursive function of which the relevant
> parts look a bit like:
>
>   sub do_stuff {
>     my $prod = 1;
>     my $recurse;
>     $recurse = sub {
>       ...
>       for my $new (@interesting_values) {
>         local $prod = $prod * $new;    # aspirational
>         $recurse->();
>       }
>     };
>     $recurse->();
>   }
>

Just a minor nit, maybe not relevant, but that will leak.

I think the reason it's not allowed was local $x predates my $x. And it was
defined to operate on globals. But you could get the same result with a
global. Just rearrange the clauses a bit. Eg, add an our $prod outside the
outer sub. Then move and change your my $prod to right before the initial
call to $recurse as a local $prod.

You could fix the leakage and use globals for $prod by changing the recurse
to

our $prod;
local *recurse = sub {};
local $prod=1;
recurse();

Solving the leak this causes is the reason we created __SUB__

Yves

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