Parentheses and Local Variables

They have: 36 posts

Joined: Oct 2004

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's picture

He has: 2,145 posts

Joined: Nov 2003

Just to clarify, which language is this?

-Greg

They have: 36 posts

Joined: Oct 2004

Sorry Greg, The language is Perl

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!Confused

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.