http://www.perlmonks.org?node_id=28716

Aighearach has asked for the wisdom of the Perl Monks concerning the following question:

i tried to find the answer by RTFM, but have you ever tried searching the documentation for "for"?!

Anyhow, here is my problem:

for LIST and for (;;) are behaving differently from what I would expect. Granted, I've never tried using for (;;) in Perl before, but I've used it a lot in C and the chess client I am working on seemed to call for it. Also, I've only used anonymous subrutines a couple times, and never as closures. After reading the section of perlfaq7 on closures, I think I understand it, but I don't understand what is going wrong in my code. So obviously I don't. Here is the code:

my ( @ref_list, $code_ref, $i ); #pass one #for SCALAR LIST for $i (1..8) { push( @ref_list, sub { print " \$i == $i\n" } ); } print "for SCALAR LIST\n"; while ( $code_ref = pop @ref_list ) { &$code_ref; } #pass 2 #for INIT ; TEST ; INCREMENT for ( $i = 1; $i <= 8; $i++ ) { push( @ref_list, sub { print " \$i == $i\n" } ); } print "for (;;)\n"; while ( $code_ref = pop @ref_list ) { &$code_ref; }

Pass 1 works as planned, but pass 2 contains a logic error. All the code refs in pass 2 output the same thing. If somebody could explain this, I would be very grateful.

Paris Sinclair    |    4a75737420416e6f74686572
pariss@efn.org    |    205065726c204861636b6572
http://sinclairinternetwork.com