Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Lexicals in if() scope gotcha!

by ambrus (Abbot)
on Mar 31, 2004 at 21:29 UTC ( #341429=note: print w/ replies, xml ) Need Help??


in reply to Lexicals in if() scope gotcha!

Update: This node is based on a mistake, the statements below are false. See Re: Re: Lexicals in if() scope gotcha!.

I fell through this trap when I wrote something like this:

for my $n (1..256) { .... do something .... } for my $n (1..32) { ... do sthg else ... }
and I got a warning for redefining $n.

The difference is that as for localizes the looping variable (even if it's not my, but a global), it's just stupid to have it outside the loop's scope. It might be useful to access it after the loop when you're writing a for(;;) loop or an if() conditional.

While this is a bit counter-intuitive for me too, it does have some logic. Perl is just not C++ (where you can put a declaration in the first argument of for(;;;)).


Comment on Re: Lexicals in if() scope gotcha!
Download Code
Replies are listed 'Best First'.
Re: Re: Lexicals in if() scope gotcha!
by liz (Monsignor) on Mar 31, 2004 at 21:49 UTC
    Are you sure?
    use strict; use warnings; foreach my $foo (1..10 ) { print $foo } foreach my $foo (1..10 ) { print $foo } __END__ 1234567891012345678910
    I'm not seeing any errors or warnings using Perl's from 5.6.2 -> 5.9.0. I would be surprised if it would produce any warnings or errors, as this is an idiom that I use myself from time to time (without warnings, I might add).

    Liz

      Ok, you're right. I can't reproduce the error now, so I must have made some error like declaring $n inside the for loop's body or something like that.

      Thanks for clarifying this.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (11)
As of 2015-07-30 15:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (271 votes), past polls