Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^5: Lexical closures

by ig (Vicar)
on Oct 26, 2008 at 01:37 UTC ( [id://719597]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Lexical closures
in thread Lexical closures

Using my on for/foreach loop variables is not merely making explicit the implicit localization that is provided by the loop: the new lexical variable is distinct from any variable of the same name (lexical or not) in the surrounding scope.

Note the difference in the following example:

#!/usr/bin/perl use strict; use warnings; use vars qw($n); $n = "global"; sub foo { my $x = shift; print "$x, $n\n"; } foreach $n (0..2) { foo($n); } print "\$n = $n\n"; foreach my $n (0..2) { foo($n); } print "\$n = $n\n";

Which produces:

0, 0 1, 1 2, 2 $n = global 0, global 1, global 2, global $n = global

After both foreach loops the global $n remains unchanged but within the first (my not used) the global is affected while within the second (my is used) the global is not affected.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-18 09:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found