Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: what is the difference between 'my' and 'local'?

by andreychek (Parson)
on Jun 22, 2001 at 05:30 UTC ( #90607=note: print w/ replies, xml ) Need Help??


in reply to what is the difference between 'my' and 'local'?

I had trouble with local when I was first getting started too. I actually found it to be a lot simpler then I had made it out to be though. Here are some definitions:

# Define a global variable, the compatible way use vars qw($foo); # Define a global variable, the Perl 5.6.x way our $foo; # Define a "lexical" variable my $foo;
Local comes in to play when you have a global/package variable defined, and you want to temporarily use that variable for something else. It often comes up with the special variables, such as $/, which is the variable which defines the input seperator. By default, it is the newline. But what if you would like to suck in an entire file, and not do it line by line? You could do this, not using local:
undef $/; # Enables whole file mode open (FH, $filename); # Opens the file while(<FH>) { # Contains the whole file blah }
That works. However, it's not considered "safe". What is considered more safe would be to use local, which would limit the scode of $/ when we undefine it like so:
{ undef local $/; open (FH, $filename); while(<FH>) { blah } }
When the last closing bracket is reached, the original value of $/ (newline by default) is restored, as the "local" definition goes out of scope.

Hope that helps!
-Eric

Update: Whoops! As Hofmator pointed out, I appear to have forgotten to actually use the local statement :-) It's now fixed. Thanks Hofmator.


Comment on Re: what is the difference between 'my' and 'local'?
Select or Download Code
Re: Re: what is the difference between 'my' and 'local'?
by Hofmator (Curate) on Jun 22, 2001 at 13:04 UTC

    In your last example you missed the localising, it should be:

    { undef local $/; # with localising open (FH, $filename); while(<FH>) { blah } }

    And then - as nobody has done this yet - I add the two definitive links to that topic, both articles from mjd found on his website Coping with Scoping and Seven useful uses of local.

    -- Hofmator

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2014-09-23 11:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (219 votes), past polls