Absolutely not! And I've illustrated a good use for it above.
However, I suppose it depends on whom you ask. Some people believe
that since "global variables considered harmful" for other, more
primitive languages, it applies to Perl as well. I disagree.
Global variables must be used with care, of course. But then,
we should be careful in all our programming, no?
jdporter The 6th Rule of Perl Club is -- There is no Rule #6.
| [reply] |
| [reply] |
Use of local is not deprecated, but it's not for creating new lexical variables. It "suppresses" the existing value of an existing variable for the lifetime of a given scope.
{
local $x = 3;
do_stuff();
}
is functionally equivalent to:
{
my $secret_name_1095471 = $x;
$x = 3;
do_stuff();
$x = $secret_name_1095471;
}
The problem with local is that it LOOKS like some handy keyword for creating locally scoped variables. But some do_stuff() might not be expecting this suppression, and they might not realize that the suppression will end without their control. No matter what do_stuff() does, the value of $x will be reverted at the end of this code's scope.
-- [ e d @ h a l l e y . c c ]
| [reply] [d/l] [select] |
... the existing value of an existing variable...
True... for global (i.e. package) variables only. local cannot be used on lexical (i.e. "my") variables.
By the same token, your illustrated functional equivalence is only correct if the $x is a global variable, not a lexical.
(Also, the equivalence breaks down if $x is tied.)
The problem with local is that it LOOKS like some handy keyword for creating locally scoped variables.
No. That's like saying "The problem with Perl is that it looks like line noise." The problem is in people's heads, not in the language itself. When you grok what the local operator does, it is delightfully useful and unsurprising.
But some do_stuff() might not be expecting this suppression, and they might not realize that the suppression will end without their control. No matter what do_stuff() does, the value of $x will be reverted at the end of this code's scope.
Right. And that is a good thing. Callees aren't supposed to care what happens after they return. If you code so that they do, you are violating some of the most basic principles of structured (not to mention
object-oriented) programming.
jdporter The 6th Rule of Perl Club is -- There is no Rule #6.
| [reply] [d/l] [select] |
Well, you can love local for what it is already, but in Perl 6 it's renamed to temp to be clearer about what it's doing. And you'll be able to use it on previously declared lexical variables.
| [reply] [d/l] [select] |