Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: I need a simple explantion of the difference between my() and local()

by mothra (Hermit)
on May 02, 2001 at 21:18 UTC ( #77421=note: print w/replies, xml ) Need Help??


in reply to I need a simple explantion of the difference between my() and local()

From perldoc perlfaq7:
What's the difference between dynamic and lexical (static) scoping? Between local() and my()?

local($x) saves away the old value of the global variable $x, and assigns a new value for the duration of the subroutine, which is visible in other functions called from that subroutine.

...

my($x) creates a new variable that is only visible in the current subroutine.

  • Comment on Re: I need a simple explantion of the difference between my() and local()

Replies are listed 'Best First'.
Re: Re: I need a simple explantion of the difference between my() and local()
by $code or die (Deacon) on May 02, 2001 at 21:25 UTC
    if you use my() inside an if .. else conditional, it is also only visible in that scope.

    There is quite thorough documentation in perlman:perlsub

    $code or die
    $ perldoc perldoc
        Update: I added an example for an if() conditional, which was the original poster's actual intent.

        I think that his implication was just a clarification of a subtlety that escapes many Perl novices.

        The point is that you don't have to use the my() declaration between curly braces to define its scope within a block of code. You can use my() within the condition of an if/else block:

        if ( (my $name = GetName()) =~ /^\w+$/) ) { print $name; }
        And the variable $name has the scope of that conditional.

        You can also use the my() declaration in a loop control statement:

        while (my $line = <>) { print $line; } foreach my $name (@people) { print $name; }
        And the variable's scope is that of the loop. It was certainly a revelation for me, once upon a time...

        buckaduck

        It seems I have err'd

        I replied to Dominus instead of mothra - which was my original intent - mothra was talking about lexical variables in subroutines. I wanted to point out that it applies to conditional blocks as well.

        $ perldoc perldoc

        Update: Nope - unless I am 'very' short-sighted - I think I did reply to mothra.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://77421]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (2)
As of 2022-05-22 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (78 votes). Check out past polls.

    Notices?