<?xml version="1.0" encoding="windows-1252"?>
<node id="994779" title="Re^3: Use of &quot;my&quot; after Perl v5.14" created="2012-09-20 19:20:04" updated="2012-09-20 19:20:04">
<type id="11">
note</type>
<author id="757127">
tobyink</author>
<data>
<field name="doctext">
&lt;p&gt;I suppose it's also worth mentioning that &lt;c&gt;my&lt;/c&gt; and &lt;c&gt;our&lt;/c&gt; have two other friends: &lt;c&gt;local&lt;/c&gt; and &lt;c&gt;state&lt;/c&gt;.&lt;/p&gt;

&lt;p&gt;&lt;c&gt;local&lt;/c&gt; sets a new, temporary value for a package variable, which expires at the end of the current scope, with the variable's original value being restored.&lt;/p&gt;

&lt;p&gt;In this example, &lt;c&gt;bar()&lt;/c&gt; sets &lt;c&gt;$::hello&lt;/c&gt; temporarily to &lt;c&gt;"Goodbye"&lt;/c&gt; and this new value is visible to &lt;c&gt;foo()&lt;/c&gt;, but after &lt;c&gt;bar()&lt;/c&gt; has finished running, the original value of &lt;c&gt;"Hello"&lt;/c&gt; is restored again.&lt;/p&gt;

&lt;code&gt;
use v5.14;

sub foo
{
	say $::hello;
}

sub bar
{
	local $::hello = "Goodbye";
	foo();
}

$::hello = "Hello";
bar();
say $::hello;
&lt;/code&gt;

&lt;p&gt;And &lt;c&gt;state&lt;/c&gt; can be used to create a variable which keeps its state, not being re-initialised.&lt;/p&gt;

&lt;code&gt;
use v5.14;

sub counter {
	state $count = 1;
	say $count++;
}

counter();
counter();
counter();
counter();
&lt;/code&gt;

&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-757127"&gt;
&lt;small&gt;&lt;small&gt;
&lt;tt&gt;perl -E'sub Monkey::do{say$_,for@_,do{($monkey=&amp;#x5B;caller(0)]-&gt;&amp;#x5B;3])=~s{::}{ }and$monkey}}"Monkey say"-&gt;Monkey::do'
&lt;/tt&gt;&lt;/small&gt;&lt;/small&gt;
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
994764</field>
<field name="parent_node">
994774</field>
</data>
</node>
