http://qs321.pair.com?node_id=1166301


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.