Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: scoping inside the loop

by LanX (Bishop)
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";


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)


expanded code example

1) see Coping with Scoping

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1034000]
[choroba]: Well, merging two hashes recursivelly is not that hard either, but...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2018-02-23 19:22 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (309 votes). Check out past polls.