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 15:42
Re: Can't localize lexical variable $x at ...
Message ID: wrote:
:On Tue, Jan 25, 2022 at 01:20:17PM +0000, 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

.. 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
It's very much a work-in-progress, but if you're interested look at for current
implementation (as one-element array).


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