"my" keyword

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

I've seen "my $this = $that;"
is it different than "$this = $that;"?
if so, how?

They have: 568 posts

Joined: Nov 1999

'my' declares the variable. it's mostly used with the 'use strict;' at the top of the script.

it saves people loads of time if they are trying to trouble shoot scripts. if you mistype a variable it will be a lot easier to find if you do use the 'use strict;' and my in front of variables.

it's also used for declaring local variables in functions.

hope that helps

They have: 850 posts

Joined: Jul 1999

Here is a little code snippet to understand it a little more.

my $fn = 'rob';
{
my $ln = 'pengelly';
print "$fn $ln"; # output: "rob pengelly"
}
print "\n$fn $ln"; # output: "rob "
'
As you can see, $ln can only be accessed inside the block, while $fn can be accessed anywhere.

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

'use strict'... is this like 'Option Explicit'?

Thanks Rob, that example helps a lot. (I can see the box of code....)

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.