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 26, 2022 02:11
Subject:
Re: Can't localize lexical variable $x at ...
Message ID:
CANgJU+X4a9a0mdjkeNdK9Z7qy-ehhP95AbCB=7T8qpaTsjbD=A@mail.gmail.com
On Tue, 25 Jan 2022 at 20:15, <yb@rslinux.fun> wrote:

> On Tue, Jan 25, 2022 at 02:37:19PM +0000, 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->();
> >   }
> >
> > .. so shadowing doesn't help. Alternatives such as a) making it a
> > one-element array, b) passing it as an argument or c) manually
> > saving and restoring are all possible, but all likely to be slower,
> > more error-prone, and add complexity to already-complex code.
> >
> > The real code's aim is to find new values for https://oeis.org/A292580.
> > It's very much a work-in-progress, but if you're interested look at
> > https://github.com/hvds/seq/blob/master/divrep/oul#L167 for current
> > implementation (as one-element array).
> >
> > Hugo
>
> Though personally I would agree with demerphq to just use a localized
> global, I think one way around this to get what you want is to write:
>
>     my $h = {prod => 1};
>     ...
>     $recurse = sub {
>         ...
>         local $h->{prod} = $h->{prod} * $new;
>         ...
>     };
>

Nod, but I might use an array instead of a hash, if speed is a concern.

Yves

-- 
perl -Mre=debug -e "/just|another|perl|hacker/"

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