Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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]
[beech]: compare MANIFEST.SKIP
[stevieb]: cheers beech. twas totally my mistake, and I got bit. When things work for so long without issue, one becomes complacent (ie. replace we/one with I ;) I've been copy/pasting that around for a few years without a hiccup, so when...
[stevieb]: choroba pointed that out, I was just, you know, *sigh*. In effect, I was lucky and fortunate

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2017-07-25 23:31 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (383 votes). Check out past polls.