in reply to Re: Re: Scope Between global and my
in thread Scope Between global and my

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 ]

Replies are listed 'Best First'.
Re: Re: Re: Re: Scope Between global and my
by jdporter (Paladin) on Apr 02, 2004 at 16:35 UTC
    ... 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.

      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.
        And you'll be able to use it on previously declared lexical variables.

        We're going to be able to dynamically localise lexicals in Perl 6 - fan-bloody-tastic! I've not used a language that can do that since my Pop-11 days :-)

        Excellent!