Gossamer Forum
Home : General : Perl Programming :

What is 'my' for ?

Quote Reply
What is 'my' for ?
I have been unable to figure this one out.

I have been seeing 'my' all over 'dbman' and 'links' scripts.

What is it for ? What if I omit it ?

Georg
Quote Reply
Re: What is 'my' for ? In reply to
From the perl docs:

Quote:
A my() declares the listed variables to be local (lexically) to the enclosing block, file, or eval(). If more than one value is listed, the list must be placed in parentheses.

What that means is that you limit the scope that the variable is available. For instance if you do:

sub mysubroutine {

my $a = 5;

}

&mysubroutine();
print $a;

you won't get any output, because $a was declared with my() and is only valid within the contents of the subroutine mysubroutine. Declaring your variables with my() prevents lots of globals hanging around, possible sideeffects due to naming conflicts and countless other problems.

Hope that helps,

Alex
Quote Reply
Re: What is 'my' for ? In reply to
Yep, thanks.


------------------
If you're feeling Dopey and Grumpy in the morning, you must be Snow White