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

Re^4: Lexical closures

by GrandFather (Sage)
on Oct 25, 2008 at 19:48 UTC ( #719541=note: print w/replies, xml ) Need Help??

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

I invariably write:

for my $i (0..3) {

so I am reminded of the scope of the loop variable and am not tempted to think of it having larger scope.

A very good rule to follow is to always declare lexical variables in the smallest scope possible which precludes declaring declaring loop variables outside the for loop scope

Perl reduces RSI - it saves typing

Replies are listed 'Best First'.
Re^5: Lexical closures
by ig (Vicar) on Oct 26, 2008 at 01:37 UTC

    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.

Re^5: Lexical closures
by backstab (Novice) on Oct 25, 2008 at 20:45 UTC

    I admit in day-to-day scripts always wanting the foreach element placeholder to be local (in the general sense) to the loop so that having it my'd as far is mandatory as chromatic showed us in the other post.

    But, we can imagine some uses in special cases as debugging, introspection or understanding dead code...

    I did a quick grep on the perl files I have installed for foreach that seems to use a global "$i". I've only found one, maybe, from

    It might be an interessing read.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2020-09-25 06:08 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (136 votes). Check out past polls.