Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is 'my' synonymous with 'local'?

Status
Not open for further replies.

AMiSM

Technical User
Jan 26, 2006
128
US
Just wondering.
 
The general rule of thumb is to always use "my" unless you have a specific reason why you want to use "local".
 
I see, so a 'local' variable is destroyed when the program leaves a block, where 'my' is almost like C's 'static'? -- a global variable with local scope and namespace?
 
You have them backwards. "my" creates lexical variables, which are destroyed at the end of the block (unless references to them remain elsewhere). "local" gives local scope to a global variable.
 

got it.
always use 'my'.
Thanks!
 
no, don't always us 'my'. use 'my' on private variables and local on global variables. This generally means perls internals:

$/
$"
etc

for example:

Code:
@array = (1..9);
{
   local $" = ',';
   print "@array"
}
print "\n";
print "@array";
 

Ok, so you can use 'local' on a special variable to make it reset when the code leaves the block. Very cool! Perl has some very interesting features!
When do you use 'local' with a user-defined variable? Is it simply a mechanism for a kind of namespace overloading?
 
You generally don't use 'local' with a user-defined variable. Probably the only place I could see it being useful would be to do the same thing that you would with a special variable...

If you have a global user-defined variable, you could local it in a smaller block of code so you don't lose the original value of it.

But generally, use 'my' most of the time.
 
I notice that when I ask questions and get given pieces of code, almost allways the variables have 'my' infront of them. Why is this?
 
It's a habit that perl coders get into once they start using "strict". For short scripts you don't have to use "strict" or "my". But if you get into the habit of using them it really does make life easier. Especially if many people contribute code to a script (such as open source scripts).
 
don't forget there is also 'our' for globals!

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top