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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Closures (was Re: for loops)
by merlyn (Sage) on Aug 20, 2000 at 21:48 UTC | |
by Aighearach (Initiate) on Aug 21, 2000 at 05:26 UTC | |
|
(Ovid) Scoping in for loops
by Ovid (Cardinal) on Aug 20, 2000 at 18:34 UTC | |
by Aighearach (Initiate) on Aug 20, 2000 at 20:09 UTC | |
|
RE (tilly) 1: for loops, closures
by tilly (Archbishop) on Aug 20, 2000 at 18:50 UTC | |
by Aighearach (Initiate) on Aug 20, 2000 at 19:48 UTC | |
by tilly (Archbishop) on Aug 20, 2000 at 21:43 UTC | |
|
Re: for loops
by jeorgen (Pilgrim) on Aug 20, 2000 at 15:39 UTC | |
by Aighearach (Initiate) on Aug 20, 2000 at 15:58 UTC | |
by tilly (Archbishop) on Aug 21, 2000 at 00:41 UTC | |
by BlaisePascal (Monk) on Aug 21, 2000 at 00:55 UTC | |
by tilly (Archbishop) on Aug 21, 2000 at 01:11 UTC | |
by Aighearach (Initiate) on Aug 21, 2000 at 05:14 UTC |