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

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

Thread Previous | Thread Next
From:
yb
Date:
January 25, 2022 19:15
Subject:
Re: Can't localize lexical variable $x at ...
Message ID:
YfBMSPX5JIMIbV9z@rslinux.fun
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;
	...
    };

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