Wednesday, October 19, 2022

Local variable and global variable example in perl

 

$number = 20;   # if my is not used then its scope is global

sub foo{
  my $number = 10;  # using my keyword for local variable
  print "Local Variable value" .$number . "\n";
}
foo(); #Will print 10 because text defined inside function is a local variable

print "global Variable value " . $number . "\n";
 
 
 
 
$num1 = 5;  # global variables
$num2 = 2;

sub multiply(){
  $::num1 = 10;
  $::num2 = 20;
  return  $num1 * $num2;
}

# When in the global scope, regular global variables can be used
# without explicitly stating '$::variablename'
print "num1 is: $num1\n";
print "num2 is: $num2\n";
print multiply();
 

No comments:

Post a Comment