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 15:42
Subject:
Re: Can't localize lexical variable $x at ...
Message ID:
202201251437.20PEbJP23697@crypt.org
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->();
  }

.. 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

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