Local variables in subroutines : Local « Subroutine « Perl






Local variables in subroutines

   

# Perl allows you to create local variables inside subroutines. 
# The local variables can have the same names as any global variables.
# The local won't overwrite the global variables.
# To make a variable local, use the my command 

#!/usr/bin/perl -w

$a = 1;
$b = 4;

# sum is global.
$sum = 10;
$value = add();

print "$a plus $b is $value.\n";
print "Global sum remains $sum.\n";

sub add {
    # This sum is local.
    my($sum) = $a + $b;

    print "Local sum=$sum.\n";
    return $sum;
}

   
    
    
  








Related examples in the same category

1.Local variable shadows the gloabl variable
2.Local variable shadows the global variable in a subroutine
3.Difference between my and local
4.Duplicate global and local variable name (use strict;)
5.Using local