Hi,

I am confused about the behavior of the subroutine that used a variable, which was declared by "my" twice in main.

use warnings; my $s = "s1"; print "define var: $s\n"; &test; my $s = "s1-2nd"; print "define var: $s\n"; &test; sub test{ print "sub: $s\n"; }

Result from the above code:

"my" variable $s masks earlier declaration in same scope at test.pl li +ne 8. define var: s1 Use of uninitialized value $s in concatenation (.) or string at test.p +l line 13. sub: define var: s1-2nd sub: s1-2nd

So the second call of &test didn't have the $s value. If I only used one "my" at the beginning (i.e. use $s = "s1-2nd", instead of my $s = "s1-2nd"), it behaved like I expected, the subroutine &test gave the value of $s each time it was called. But as shown above, by just adding "my" and declaring the $s second time, the first call of &test had $s value as uninitialized. Why did this happen?

If I placed the subroutine at the beginning, such as:

use warnings; my $s = "s1"; print "define var: $s\n"; &test; sub test{ print "sub: $s\n"; } my $s = "s1-2nd"; print "define var: $s\n"; &test;

This time, the result is:

"my" variable $s masks earlier declaration in same scope at test.pl li +ne 12. define var: s1 sub: s1 define var: s1-2nd sub: s1

So the second call of &test did have the $s value but the value was from the first declaration. Why did the second $s value not overwrite the first when there is a second "my"?
Again, if I simply remove the second "my", the result would be expected:

define var: s1 sub: s1 define var: s1-2nd sub: s1-2nd

Thanks in advance for your kind reply.

ark


In reply to how subroutine functions when declare "my" twice in main by Anonymous Monk

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.