The difference between my and local

rajeshkumar created the topic: The difference between my and local

There is a subtle difference.

In the example below, $::a refers to $a in the ‘global’ namespace.
‘local’ temporarily changes the value of the variable, but only within the scope it exists in.
$a = 3.14159;
{
local $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}

print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs In block,

# This outputs
In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

‘my’ has no effect on the global $a, even inside the block.

$a = 3.14159;
{
my $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}
print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

Regards,
Rajesh Kumar
Twitt me @ twitter.com/RajeshKumarIn

scmuser replied the topic: Re: The difference between my and local

With more explanation…

Both of them are used to declare local variables.
The variables declared with “my” can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with “local” can live within the block and have its visibility in the functions called within that block.

Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x