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

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

Thread Previous | Thread Next
January 25, 2022 16:48
Re: Can't localize lexical variable $x at ...
Message ID:
demerphq <> wrote:
:On Tue, 25 Jan 2022, 23:43 , <> 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
:our $prod;
:local *recurse = sub {};
:local $prod=1;

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

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


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About