
Question:
Implementing dynamic scoping, I was using <strong><a href="http://perldoc.perl.org/functions/local.html" rel="nofollow">local
</a></strong>. Then I came across <strong><a href="http://perl.plover.com/FAQs/Namespaces.html" rel="nofollow">this</a></strong> post, which says the following:
Why have local at all? The answer is 90% history. Early versions of Perl only had global variables. local was very easy to implement, and was added to Perl 4 as a partial solution to the local variable problem.
</blockquote><strong>...never use local.</strong>
Is its use deprecated, or discouraged? If yes, what is the alternative?
Answer1:The post you linked to is misleading, or at least incomplete. It is true that you should never use local
to create a lexical variable. It doesn't do so, and that is what my
is for.
However, you <em>should</em> use local
when you need its actual functionality: giving a temporary value to a global variable. This is most often used for temporarily setting Perl's special variables. A classic case is something like this:
{
local $/;
$entire_file = <$filehandle>;
}
In order to read an entire file at once, you need to set the record separator to undefined. But you only want to do that temporarily; hence local
should be used.
This is absolutely not discouraged. It is considered good Perl code.
<strong>Update:</strong> I see that the article actually has a note which qualifies its "never use local" statement. Still, I think it is misleading to make such a blanket statement. I agree with the critics to which the note is responding. The example above is quite a common, basic case, and there are several other common uses of local
in that vein, as well.
I understand that a beginners' tutorial needs to keep things simple, but simple doesn't have to mean inaccurate. <em>"For now, don't worry about local
; just use my
"</em> would be just as clear and simple, but wouldn't mislead someone into thinking that local should <em>never</em> be used.
Use my
to create a local variable, which is most of the time what people want.
It's fine to use local
for the thing that only local
does: setting a different value to a global variable, which will be restored after the current block. That is in no way deprecated. It's stable, well-supported, and is a key Perl feature. (However, it happens not to be something people tend to want any where near as often as creating a local variable. In particular many beginners never need to do this.)
What is discouraged is using local
to attempt to create a local variable, because that's what my
should be used for. There is never any reason to use local
for this.
It's not bad advice, actually. As with all programming dicta, the unspoken addendum is <a href="http://senseis.xmp.net/?ProverbsDoNotApplyToWhite" rel="nofollow">"unless you really know what you're doing"</a>. There are legitimate use cases for local
. But in general, if you think local
is the right tool, you should reconsider before proceeding.