Parentheses and Local Variables
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
Greg K posted this at 01:31 — 18th August 2006.
He has: 2,145 posts
Joined: Nov 2003
Just to clarify, which language is this?
-Greg
StuPeas posted this at 08:28 — 18th August 2006.
They have: 36 posts
Joined: Oct 2004
Sorry Greg, The language is Perl
StuPeas posted this at 11:51 — 18th August 2006.
They have: 36 posts
Joined: Oct 2004
It appears that after my laptop has been off for the night, the behaviour explained has vanished, and both parentheses and no parentheses give the same result.
I cant explain it, but there you go!
THANX anyway
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.