linux poison RSS
linux poison Email

Perl Script: Difference between local and my variables

'my' creates a new variable (but only within the scope it exists in), 'local' temporarily amends the value of a variable

ie, 'local' temporarily changes the value of the variable (or global variable), but only within the scope it exists in.

So with local you basically suspend the use of that global variable, and use a "local value" to work with it. So local creates a temporary scope for a temporary variable.

Below script explains the concepts of local Vs my variables



Source : cat local_my.pl
#!/usr/bin/perl

print " ----- local example ------ \n";
$a = 10;
{
  local $a = 20;
  print "Inside block \$a    : $a \n";
  print "Inside block: \$::a : $::a \n";
}

print "Outside block \$a   : $a \n";
print "Outside block: \$::a: $::a \n";
print " ----- my example ------ \n";
$b = 10;
{
  my $b = 20;
  print "Inside block \$b    : $b \n";
  print "Inside block: \$::b : $::b \n";


print "Inside block \$b    : $b \n";
print "Inside block: \$::b : $::b \n";

Output: perl local_my.pl
 ----- local example ------
Inside block $a    : 20
Inside block: $::a : 20
Outside block $a   : 10
Outside block: $::a: 10
 ----- my example ------
Inside block $b    : 20
Inside block: $::b : 10
Inside block $b    : 10
Inside block: $::b : 10




0 comments:

Post a Comment

Related Posts with Thumbnails