in reply to naming anonymous subroutines inner variables
Do:
for (keys %{$self->{SQL}}) { my $closure = $_; $self->{$_} = $self->{DBO}->prepare($self->{SQL}->{$_}); $self->{"f$_"} = sub { my $self = shift; my @res; $self->{ $closure }->execute(@_); while (my $dbrow = $self->{ $closure }->fe +tchrow_hashref()) { push @res, \$dbrow; } return \@res; }; }
What you have at the moment is like this:
undef %h; for( qw[ the quick brown fox ] ){ $h{ $_ } = sub { print "$_"; }; }; pp \%h; do { my $a = { brown => sub { "???" }, fox => 'fix', quick => 'fix', the +=> 'fix' }; $a->{fox} = $a->{brown}; $a->{quick} = $a->{brown}; $a->{the} = $a->{brown}; $a; } $_='joe'; for my $key ( keys %h ) { $h{ $key }->(); };; joe joe joe joe
Ie. The subroutine is referencing the variable $_; and when it is called, it will use whatever the current value of $_ happens to be at the time.
What you need is this which creates a separate closure for each subroutine instantiated in the loop:
undef %h; for( qw[ the quick brown fox ] ){ my $closure = $_; $h{ $_ } = sub { print $closure; }; }; pp \%h; { brown => sub { "???" }, fox => sub { "???" }, quick => sub { "???" }, the => sub { "???" }, } $_='joe'; for my $key ( keys %h ) { $h{ $key }->(); };; the fox brown quick
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice. Not understood.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: naming anonymous subroutines inner variables
by writch (Sexton) on Jun 22, 2016 at 21:09 UTC | |
by BrowserUk (Patriarch) on Jun 22, 2016 at 21:15 UTC |
In Section
Seekers of Perl Wisdom