Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

(Ovid) Re: my and local differences

by Ovid (Cardinal)
on Nov 10, 2000 at 23:11 UTC ( [id://40999]=note: print w/replies, xml ) Need Help??


in reply to my and local differences

It looks like you are right. my does seem to be a better fit here. However, the following might be even more appropriate, given your description:
use constant EB => "\034";
That has the advantage that every knows it's a constant and not subject to change. Of course, if all you are doing is documenting, this may not be an option.
I have strict in use all the time, but I have only ever used my(), so I'm not clear on the difference.
local pushes the current copy of the variables value (if any) onto a stack and assigns a new value which is available to everything within the original scope of local. When that variable passes out of scope, the original value is pulled from the stack and restored. In practice, local is rarely needed, unless my cannot be used.

Global punctuation variables, for example, cannot be declared lexically with my and therefore must use local if you wish to constrain their scope.

open FILE, $somefile or die $!; { local $/; # slurp mode $foo = <FILE>; } close FILE;
The above snippet uses "slurp mode" to read the entire contents of a file into a scalar. local is in a block to ensure that the change to $/ does not affect other portions of the program (since $/ is global).

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

Replies are listed 'Best First'.
RE: (Ovid) Re: my and local differences
by HaB (Sexton) on Nov 10, 2000 at 23:29 UTC
    First, thanks to everyone for the comments...all of that helps.
    I think the reason I've never had to use local before is that I A - rarely mess with the values to punctuation vars, and B - almost always explicitly pass a value to a subroutine that requires one, instead of relying on the global value. IOW, I use my($var) in a sub, and if I call any other routines in the sub using that var, I call them with my_sub($var);

    I guess it's just weird that it has never come up before.


    -HaB


    hword.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-07-17 12:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.