B
Bill Smith
My "Case 1" creates an array of references to anonymous subroutines.
Each subroutine is intended to print the value of the loop index ($i)
when it (the subroutine) was created. One of the subroutines is
executed to demonstrate that the wrong value is printed. (The index is
never 3)
"Case 2" is an experimental version which solves the problem by using
another variable ($j) as the loop index
and making $i a lexical variable within the scope of the loop.
use strict;
use warnings;
my @ref1;
for (my $i = 0; $i < 3; $i++){
$ref1[$i] = sub{print "Case 1 = $i WRONG\n"};
}
&{$ref1[1]};
for (my $j = 0; $j < 3; $j++){
my $i = $j;
$ref1[$i] = sub{print "Case 2 = $i OK\n"};
}
&{$ref1[1]};
__END__
What is wrong with "Case 1"? I first encountered the problem in a Tk
application and wrote this case as a aide to solving it. The successful
"Case 2" was found by trial and error. Both appear to conform to
section of "Programming Perl" on closures.
Thanks,
Bill
Each subroutine is intended to print the value of the loop index ($i)
when it (the subroutine) was created. One of the subroutines is
executed to demonstrate that the wrong value is printed. (The index is
never 3)
"Case 2" is an experimental version which solves the problem by using
another variable ($j) as the loop index
and making $i a lexical variable within the scope of the loop.
use strict;
use warnings;
my @ref1;
for (my $i = 0; $i < 3; $i++){
$ref1[$i] = sub{print "Case 1 = $i WRONG\n"};
}
&{$ref1[1]};
for (my $j = 0; $j < 3; $j++){
my $i = $j;
$ref1[$i] = sub{print "Case 2 = $i OK\n"};
}
&{$ref1[1]};
__END__
What is wrong with "Case 1"? I first encountered the problem in a Tk
application and wrote this case as a aide to solving it. The successful
"Case 2" was found by trial and error. Both appear to conform to
section of "Programming Perl" on closures.
Thanks,
Bill