Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Scope Difference

by tedv (Pilgrim)
on May 02, 2001 at 21:21 UTC ( #77424=note: print w/ replies, xml ) Need Help??


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

The difference between my and local is just one of scope. All subroutines called from the context of a local variable can access that variable, but not the my variable:

sub foo { local $a = 10; my $b = 20; bar(); } sub bar { print "A: $a\n"; # Just fine print "B: $b\n"; # Warning from -w }

If a piece of code needs to use local in this way, it's could probably be rewritten in a cleaner way. If my works, you should definitly use it.

I won't condemn all use of local, however. I believe there are situations where you need to use local for dynamically generated anonymous functions, perhaps for use with $SIG{XYZ}. Can anyone confirm or deny this? I just remember writing signal code once where I needed to use local. (Of course, this is before I learned about the signal handling packages at CPAN.)

-Ted


Comment on Scope Difference
Select or Download Code
Replies are listed 'Best First'.
Re: Scope Difference
by TGI (Vicar) on May 02, 2001 at 21:55 UTC

    A good use of local is when you are tweaking a special variable.

    Let's say you want to slurp a whole file into a scalar. Your code would look something like this:

    my $file; { local $/; open (FILE, "<$foo") or die "Unable to open $foo: $!"; $file = <FILE>; close FILE; }

    By enclosing the modification of $/ in a block, you avoid surprises down the road. $/ only has its value changed within that block.


    TGI says moo

      By narrowing the block that holds the local, you can further contain the effect.
      open(FILE, "<$foo") or die "$foo: $!"; my $file = do { local $/; <FILE> }; close(FILE);

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2015-07-08 02:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls