in reply to Local Scope Variables

This is really, really bizarre. I'm using 5.8.1-RC3 in MacOS X 10.3. Here is what I've found:-

If I comment out the lines of test2, then change local $aa =... to local $b = I get no errors. If I change the '$a' assignment to something with 2 letters then I get another error due to that line. I seems as though perl only generates the global symbol error for variables with more than one letter in their name. Very strange.

The obvious way to fix the problem is to do what the error messages are asking for - give a global package name by putting $main::aa

This is not a very good idea though. In general you would be better to pass parameters into the function, and use return values from a function to achieve what you want. Only use global variables as an absolute last resort. (I've never used the 'local' decleration by the way!)

use strict; test1(); sub test1 { test2(1,2); } sub test2 { my ($a, $aa) = @_; print "a = $a\n"; print "aa = $aa\n"; }

Replies are listed 'Best First'.
Re: Re: Local Scope Variables
by arden (Curate) on Feb 13, 2004 at 01:26 UTC
    hhdave, see borisz's response above yours. Basically, $a and $b are on the short list of special variables that are automatically declared by perl, so they already exist in any scope.

    As of perl 5.6, you should probably just use my instead of local anyway, but use a variable with meaning to you, not a special one like $a or $b. . .