Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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!

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

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://90607]
NodeReaper stumbles on his way to the attic

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2018-01-21 09:36 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (227 votes). Check out past polls.