What's going on here?

The second my $foo masks the first; you know that. So the compiler allots different slots for them. Now, the sub foo happens to be in the same scope as that second my $foo, but at the time you call that function, it has not gotten a value assigned, so it is undef.

use Devel::Peek; use strict; $|=1; my $foo = 1; print "1st foo: "; Dump($foo); foo(); my $foo = 2; print "2nd foo: "; Dump($foo); sub foo { print "sub foo: "; Dump($foo); print "foo: $foo\n"; } __END__ 1st foo: SV = IV(0x99b1c8c) at 0x9996768 REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 1 sub foo: SV = NULL(0x0) at 0x9996a8c REFCNT = 2 FLAGS = (PADBUSY,PADMY) foo: 2nd foo: SV = PVIV(0x9997b10) at 0x9996a8c REFCNT = 2 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 2 PV = 0

The second my $foo is allocated at 0x9996a8c, and that's the one seen in the sub.


In reply to Re: Scope surprise by shmem
in thread Scope surprise by smcdonald

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.