Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

RE: RE (tilly) 3 (closures): for loops

by BlaisePascal (Monk)
on Aug 21, 2000 at 00:55 UTC ( [id://28741]=note: print w/replies, xml ) Need Help??


in reply to RE (tilly) 3 (closures): for loops
in thread for loops, closures

if I understand correctly, what you are saying is that:
my @coderefs; for $i (@array) { push @coderefs, sub { print $i; }; }
is (roughly) equivilant, scope-wise, to:
my @coderefs; for (@array) { my $i = \$_; push @coderefs, sub { print $$i; }; }
In the second case, it is abundantly clear that the $i captured by the closure is different for each iteration, and is an alias for the underlying array element.

Replies are listed 'Best First'.
RE (tilly) 5 (closures): for loops
by tilly (Archbishop) on Aug 21, 2000 at 01:11 UTC
    Exactly. See my example at RE (tilly) 3: for loops, closures to see how you can demonstrate this by modifying the array elements after you create the closure. From perlsyn:

    The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
    It is directly aliased. If you modify the element that you are iterating over, you modify the elements of the array, if you modify the elements of the array you modify the element that you are iterating over, and if you create a closure that temporary aliasing becomes longer-lived.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://28741]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (7)
As of 2024-04-19 16:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found