Welcome, Guest
Username Password: Remember me

The difference between my and local
(1 viewing) (1) Guest
Perl Script
  • Page:
  • 1

TOPIC: The difference between my and local

The difference between my and local 1 year, 5 months ago #448

  • rajeshkumar
  • OFFLINE
  • Moderator
  • I love software configuration management
  • Posts: 370
  • Points: 44563
  • Karma: 4
  • Honor Medal 2009
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
Build and Release Engineer
My Blog: community.scmgalaxy.com/pg/profile/rajeshkumar

Re: The difference between my and local 1 year, 5 months ago #455

  • scmuser
  • OFFLINE
  • Gold Boarder
  • scm master
  • Posts: 237
  • Points: 3427
  • Karma: 0
  • Honor Medal 2009
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.
  • Page:
  • 1
Time to create page: 0.95 seconds

     
    
Home Forum