While that code snippet is correct, the first paragraph of explanation is actually partially wrong.

.... it creates a kind of global variable with restricted scope! If this is in a subroutine, the second time you call the sub, you get exactly the same array, not a new one.

This is not true. Look at the following:

use strict; use warnings; sub mytest { my $var if 0; $var++; print $var, "\n"; } mytest(); mytest(); __OUTPUT__ 1 1

We see several important things in that snippet. First, there are NO errors under strictures, and no warnings. Second, $var is NOT the same variable each time mytest() is called. If we had created a closure, the output would have been 1 and 2, not 1 and 1. If we had autovivified a global, we would have gotten a strictures error, or at minimum, the output would have been 1 and 2. But none of that happens. We get a new lexical variable each time mysub() is called.

Why?

Because my has two elements to how it works. First, the compiletime side. At compiletime, the framework is made for a lexical variable. Yet at compiletime, it is too soon to know the outcome of program logic. So the lexical is created without any regard for logic; all that matters is lexical scope.

At runtime, logic springs to life. And if the "my" declaration has an assignment component to it, as in  my $x = 10 if $condition; that assignment will only take place if $condition is true. But $x exists within the lexical block whether or not $condition is ever true. And it falls out of scope just like any good lexical would, when the lexical block ends, even if its a subroutine.


Dave


In reply to Re: Re: declaring same variable by davido
in thread declaring same variable by samy1212

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.