Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Declaring a Variable [for BEGINNERS]

by scooper (Novice)
on Dec 28, 2006 at 04:26 UTC ( #591978=note: print w/replies, xml ) Need Help??

in reply to Declaring a Variable [for BEGINNERS]

Always put the for loop iterator variables as 'my' inside the for loop.
foreach my $region (@regions) { # something happening in the loop }
If you write
my $region foreach $region (@regions) { # something happening in the loop }
Perl silently declares a new lexical variable (also named $region) as the iterator variable. The new $region is scoped to the loop block and hides any variable $region from the outer scope. By explicitly putting the my in the foreach, you're reminding yourself of this behaviour. You're avoiding the misconception that the last value of $region will be available after the for loop (it won't, however you try to scope it). If you want that information you have to save it to an outside variable inside the loop
my $latest_region; foreach my $region (@regions) { $latest_region = $region; # something happening in the loop last if (some condition); } print "last region considered was $latest_region\n";
Most of this information lifted from "Non-Lexical Loop Iterators", 'Always declare a for loop iterator variable with my', in "Perl Best Practices", by Damian Conway

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://591978]
[LanX]: Not fair ... I'm totally ignoring the doping games...
[Corion]: Huh? That's weird indeed... Also, I thought that the olympic games were over already, but obviously not ;)
[choroba]: And we lost to unknown sportspersons with no official dresses
[choroba]: Russia didn't send them officially, they're on vacation in Korea
[LanX]: no that was Syria! ;-)
[LanX]: And the reason is: The world’s best players aren’t at this year’s Games after the NHL stopped its athletes from leaving in the middle of the season. ... LOL
[LanX]: horoba: you like ice hockey?
[choroba]: Like is a too strong word. But you can't evade it here.
LanX (for people wondering: yes field hockey still exists and is even more popular than Hasslhoff in Germany)
[Corion]: LanX: Ah, that explains a lot :)

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (9)
As of 2018-02-23 16:28 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (303 votes). Check out past polls.