Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^5: Lexical closures

by ig (Vicar)
on Oct 26, 2008 at 01:37 UTC ( #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
Node Status?
node history
Node Type: note [id://719597]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2019-07-24 02:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?






    Results (32 votes). Check out past polls.

    Notices?