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 MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using "my" 1

Status
Not open for further replies.

Edge118

Programmer
Jun 15, 2004
104
US
If I don't include 'my' when I define my variables, are they global then even if they are inside a loop?

"Pin me. Perl me."

Regards,

Chris
 
Also, can someone elaborate on what the point of 'my' is?

Thanks

"Pin me. Perl me."

Regards,

Chris
 
The keyword my essentially restricts the scope of a variable to the block in which it is declared. It is much more complicated than that, but that, as I understand it, is the gist of it.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Is it good practice to use 'my' when using variables in my Perl scripts?

"Pin me. Perl me."

Regards,

Chris
 
Yes I think it is very good practices. If for no other reason than that if you use my and use strict; then you will never spend days searching for where you accidentally mispelled some variable name.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
unless you say otherwise, all perl variables are global.

thus, the need for "my, local, our".

As in all searches for enlightenment - google:
"perl tutorial my variable
 
if you declare it as "my" at the top of main, without being inside of a loop, or elsewhere, I think that still means it is global.

___________________________________
[morse]--... ...--[/morse], Eric.
 
Use the STRICT statement and try to run your script without using MY.

There's always a better way. The fun is trying to find it!
 
The general rule of thumb is always to use 'my' unless you have a particular reason to use 'local' or 'our'.

nawlej - declaring a variable with 'my' *never* makes it global. If you happen to do so at the top of the script, then it will still be in scope anywhere in that package but won't be visible from any other package.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top