Click to See Complete Forum and Search --> : Parentheses and local variables


StuPeas
08-17-2006, 05:17 PM
In the code below it seems that surrounding the variable name ($total) in parentheses when declaring it as local (in the sub "change_total"), gives a different output, (when the last call to sub show_total is executed), than if the variable appears without parentheses.

If the parentheses are left off, the last call to sub show_total accesses the global version of $total instead.

The output of the script is as follows:

With brackets
0
5
5

Without brackets
0
5
0

$total = 0;
show_total();
change_total();
show_total();

sub change_total
{
local($total) = 5;
show_total();
}

sub show_total
{
print('$total equals '. "$total\n");
}


I would be greatful if someone could explain the difference to me.

THANX

NogDog
08-17-2006, 05:30 PM
You probably should be using my rather than local. See: http://perl.plover.com/FAQs/Namespaces.html#C_local_and_C_my_

StuPeas
08-17-2006, 05:39 PM
thanx for the responce, but the question still stands.
I understand that using "my" would be better, but I am trying to learn perl and it is the answer to the question that is important to me as it is probably an important point the applies in other places too.
I am greatful for the responce and the good advice though. :)

NogDog
08-17-2006, 06:11 PM
It probably has something to do with the following, though I don't claim to completely understand it myself:

A local is simply a modifier on an lvalue expression. When you assign to a localized variable, the local doesn't change whether its list is viewed as a scalar or an array. So

local($foo) = <STDIN>;
local @FOO = <STDIN>;

both supply a list context to the right-hand side, while

local $foo = <STDIN>;

supplies a scalar context.

(From http://www.ayni.com/perldoc/perl5.8.0/pod/perlsub.html#Temporary-Values-via-local() )

StuPeas
08-18-2006, 01:16 PM
It appears to have been some sort of wierd problem with my pc, becouse when i switched it back on this morning and ran the code again I got the result that I shoul have (the parentheses made no difference at all.

Thanx for all the help though--Im just about to post a new thread which should be simple for the guys here (I hope)