Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The purpose of a local variable in subroutine 3

Status
Not open for further replies.

szzxy

Technical User
Aug 14, 2010
8
CA
Hello Perl experts,
I recently self-learn about the subroutine.
When do we need a local variables in the subroutine? Illustration with an example will be great!

Here is one example I have:
"
sub add{
local ($sum);
$sum=o;

foreach $_(@_){
$sum+=$_;
}

$sum;
}


"

I am totally confused by the local ($sum)here. What will happen, if we don't use the local() but just initialize a $sum?

Regards,
szzxy






 
Local() variables are a feature of Perl 4 whose use is now discouraged in Perl 5. Instead you should use my() variables. There are also our() variables that (I believe) are shared between packages (or classes). My() variables were introduced in Perl 5. Our() variables were introduced in later versions of Perl 5.

There are some differences between my() and local().

Declaring a variable as local() incurs slightly more overhead than my(). If your routine declares local($sum) and then calls another routine that has the same declaration, Perl realizes that it must keep track of 2 $sum variables. Therefore Perl saves the value of $sum from the first routine and restore it when control returns back. Perl does not need to do this for my() variables because each my() variable with the same name has its own address space.

If your routine calls another routine, the called routine will not be able to see the my() variable as it will the local() variable. However, if the my() variable is declared in the in body of the main program (or package or class) it is visible to all the subroutines - just like local() variables are.

If you remove the local() declaration, the $sum variable would be visible throughout your entire program - not just from your subroutine downwards to other routines, but also upwards through the calling chain. My() variables are only visible to the routine they are declared in.

Since my() variables are not part of Perl's "symbol table" as local() variables are, they are not visible to the debugger's "X" command. The "X" command is handy to nicely display the contents of an array or hash. So if the array or hash is declared with my(), the"X" command will not display it. For this reason, I may temporarily, declare arrays and hashes as local() when debugging my program and then change them back to my().
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top