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

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

Thread Previous | Thread Next
From:
David Nicol
Date:
January 26, 2022 05:59
Subject:
Re: Can't localize lexical variable $x at ...
Message ID:
CAFwScO8N7fuhCjpyi91oFKpr+GH1yiUG1BNnrXhPZ9-099Zcqg@mail.gmail.com
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.
>

okay here's my rewrite. I started with (c) then switched to (b).

 sub do_stuff {
      my $prod = shift;
      my @interesting_values = wassup($prod);
      for my $new (@interesting_values) {
           do_stuff($prod * $new);
      }
 };
 do_stuff(1);

I for one think passing an argument to a named recursive routine is less
error-prone and less complicated than trying to do arcane and fragile perl
four magic on a variable you're passing by shared outer scope to inner
iterations of an anonymous one.

It seems like it might be a good case for ditching recursion altogether in
favor of a generator/consumer pattern.

      my @queue = (1);
      while(@queue){
            my $prod = shift @queue;
            # push @queue, map { $prod * $_ } wassup($prod);  # one way to
do it
            push @queue, $prod * $_  for wassup($prod);  # another way to
do it
      }




-- 
"Lay off that whiskey, and let that cocaine be!" -- Johnny Cash

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