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

Re: scoping inside the loop

by LanX (Canon)
on May 17, 2013 at 17:59 UTC ( #1034000=note: print w/ replies, xml ) Need Help??


in reply to scoping inside the loop

  • Case1: you're resetting $i each time at the beginning
  • Case3 the $i scoped within the block is differentš from the outer one
    (update: and you are resetting the inner one each time again)

Generally better use prefix-constructs like

while () {...} , until () {...} or  for (;;) {...}

e.g. Case 3:

use strict; use warnings; my $i=42; print "outside: $i\n"; for (my $i=5; $i>0; $i--) { print "inside: $i\n"; }; print "outside: $i\n"; my $j=666; print "outside: $j\n"; { my $j=5; do { print"inside: $j\n"; $j--; } until($j<=0) } print "outside: $j\n";

prints:

outside: 42 inside: 5 inside: 4 inside: 3 inside: 2 inside: 1 outside: 42 outside: 666 inside: 5 inside: 4 inside: 3 inside: 2 inside: 1 outside: 666

As you can see, does the postfix construction force you to an extra block to limit the scope of the inner $j.

Cheers Rolf

( addicted to the Perl Programming Language)

Update

expanded code example

Footnotes
1) see Coping with Scoping


Comment on Re: scoping inside the loop
Select or Download Code
Replies are listed 'Best First'.
Re^2: scoping inside the loop
by Anonymous Monk on May 17, 2013 at 18:36 UTC

    Thanks LanX.Understood but in second case which is a working condition $i's scope is in outer loop but how it got tucked in to inside loop.My understanding is if my is before a variable it's existence is strictly with in that boundary. In case 2 my is associated with $i so i think it only resides outside or where it is defined but i am confused how it got transported to loop.

      No, up to the point that you declare an inner $i with my the outer one is used.

      No inner my $i means the outer one is everywhere available.

      These are universal rules for lexical variables in almost any language!

      Have a look at the scoping-article I linked.

      Cheers Rolf

      ( addicted to the Perl Programming Language)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2015-07-07 23:49 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 (93 votes), past polls