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

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

Thread Previous | Thread Next
From:
hv
Date:
January 25, 2022 16:48
Subject:
Re: Can't localize lexical variable $x at ...
Message ID:
202201251543.20PFhPP24164@crypt.org
demerphq <demerphq@gmail.com> wrote:
:On Tue, 25 Jan 2022, 23:43 , <hv@crypt.org> wrote:
:> 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.
[...]
:Solving the leak this causes is the reason we created __SUB__

Ah good point - not hugely relevant in this case (the outer sub is called
at most once), but I had forgotten about __SUB__.

: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();

Just changing the inner call to '__SUB__->()' is enough to fix the leak,
right?

We avoid using globals for good reasons, I wouldn't want to use them
for this unless there really was no alternative.

Hugo

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