perltutorial
cLive ;-)
Well, this confused the hell out of me, so I thought I'd spend some time getting my head around it.
<P>Probably best to show by example (apologies to Joseph Hall and [merlyn] for borrowing heavily here from <A HREF="http://www.amazon.com/exec/obidos/ASIN/0201419750/102-5465082-9004914">Effective Perl Programming</A>)
<P>Quick summary: <I>'my' creates a new variable, 'local' temporarily amends the value of a variable</I>
<P>There is a subtle difference.
<P>In the example below, $::a refers to $a in the 'global' namespace.
<CODE>
$a = 3.14159;
{
local $a = 3;
print "In block, \$a = $a\n";
print "In block, \$::a = $::a\n";
}
print "Outside block, \$a = $a\n";
print "Outside block, \$::a = $::a\n";
# This outputs
In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159
</CODE>
<P>ie, 'local' <B>temporarily changes the value of the variable</B>, but <I>only within the scope it exists in</I>.
<P>so how does that differ from 'my'? 'my' creates a variable that does not appear in the symbol table, and does not exist outside of the scope that it appears in. So using similar code:
<CODE>
$a = 3.14159;
{
my $a = 3;
print "In block, \$a = $a\n";
print "In block, \$::a = $::a\n";
}
print "Outside block, \$a = $a\n";
print "Outside block, \$::a = $::a\n";
# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159
</CODE>
<P>ie, 'my' has no effect on the global $a, even inside the block.
<H4>But in real life, they work virtually the same?</H4>
<P>Yes. Sort of. So when should you use them?
<UL>
<LI>use 'my' when you can (it's faster than local)
<LI>use local when:
<UL>
<LI>you're amending code written in Perl 4, unless you are sure that changing 'local' to 'my' will not cause any lexical problems
<LI>you want to amend a special Perl variable, eg $/ when reading in a file. <B>my $/;</B> throws a compile-time error
</UL>
</UL>
<P>If you use Perl 5 and strict (and I know you do :), you probably haven't noticed any difference between using 'my' and 'local', but will hopefully only use 'local' in the second instance above.
<P>EPP also suggests you use 'local' when messing with variables in another module's namespace, but I can't think of a RL situation where that could be justified - why not just scope a local variable? Perhaps someone could enlighten me?
<P>But, if you ever end up amending some old Perl 4 code that uses local, you need to be aware of the issues and not just do a <CODE>s/\blocal\b/my/gs</CODE> on the script :) - sometimes people use the 'features' of local in unusual ways...
<P>Hope that's cleared a few things up.
<P>cLive ;-)