Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: naming anonymous subroutines inner variables

by AnomalousMonk (Archbishop)
on Jun 22, 2016 at 20:17 UTC ( #1166301=note: print w/replies, xml ) Need Help??

in reply to naming anonymous subroutines inner variables

For the anon subroutine to access each key at its | the subroutine's runtime, it needs to create a closure over a lexical variable (not, of course, access the global $_ variable) when the subroutine is created. Try something like (untested):

for my $k (keys %{$self->{SQL}}) { ...; $self->{"f$k"} = sub { ...; $self->{$k}->execute(@_); while (my $dbrow = $self->{$k}->fetchrow_ +hashref()) { ...; } return ...; }; }
Basically, all the  $_ scalars become  $k scalars.

Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: naming anonymous subroutines inner variables
by writch (Sexton) on Jun 22, 2016 at 20:29 UTC
    Didn't do anything except make the value that fails $self->{$k} instead of $self->{$_}.
      Works for me:
      #!/usr/bin/env perl use 5.014; use strict; use warnings; my $self; for my $k (qw(foo bar baz)) { $self->{$k} = sub { return join $k, @_ }; $self->{"f_$k"} = sub { my $self = shift; return $self->{$k}->(@_); }; } for my $k (qw(foo bar baz)) { say $self->{"f_$k"}->($self, qw(a b c)); } __END__ afoobfooc abarbbarc abazbbazc
      It would be more productive if you would show something we could actually run.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1166301]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2022-11-29 02:12 GMT
Find Nodes?
    Voting Booth?