Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is important to distinguish between <em>visibility</em> and <em>lifetime</em>.</p> <p>The <em>visibility</em> of variables declared using <code>our</code> or <code>my</code> is identical. You can used the name anywhere after the declaration before the first enclosing brace or end of file.</p> <p>Beware that this doesn't apply to <em>full-qualified</em> variable names, which need no declaration and can be accessed anywhere. Without declaring anything I can assign to a package variable</p> <pre><code>$pack::three = 3; </code></pre> <p>and use that anywhere else in any package. I don't even have to declare the <code>pack</code> package. But if I write</p> <pre><code>package pack; our $three; </code></pre> <p>I have generated an shortened <em>alias</em> for <code>$pack::three</code> that I can use within the same lexical scope as I could a <code>my</code> variable in the same place: before an enclosing brace or end of file.</p> <p>These package variables are always available from the start of the program's execution. Just like hash elements you can always assign to a new one and it will always be there - their <em>lifetime</em> is endless. In fact package variables <em>are</em> hash elements to all intents and purposes.</p> <p>Lexical variables, declared with <code>my</code>, on the other hand, are created at the point of declaration and destroyed once they go out of scope and there is no reference to them held anywhere. So, unless you take the reference of such a variable, its <em>lifetime</em> is the same as its <em>visibility</em>. A <code>my</code> declaration inside a loop causes a new variable to be created and destroyed for each execution the loop.</p> <p>In your code, you have created an alias <code>$val</code> for package variable <code>$one::val</code> and a lexical variable <code>$new</code>. Neither are within a code block so both are visible to the end of the file. The <code>package two</code> has no effect at all here, but if you had written <code>our $val</code> <em>after</em> that second package statement you would have changed the alias <code>$val</code> to indicate <code>$two::val</code> instead.</p> <p>I hope that helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload