[Wellington-pm] A question about scopes

Jacinta Richardson jarich at perltraining.com.au
Tue Mar 28 13:33:16 PST 2006

Cliff Pratt wrote:

>>package bar;
>>my $foo = 7;         # $foo in the bar package (generates warning if in
>>                       same file as above code)
>>print "$foo\n";      # prints "7".
>>print $main::foo;    # undefined!
>>print $main::bar;    # undefined!
>>print "$bar\n";      # prints "10" but only if this is all in the same file
>>$main::foo is undefined because $foo was declared with "my".  Declaring a
>>variable with "my" means that it lasts from that location to the end of the
>>enclosing block ( }  or end of tile ).  "my" variables are not "package"
>>variables, but are rather lexical variables.
> I understand this and I don't understand this! Yes, I see what you are 
> saying, but doesn't $main:: say to look in $main's Symbol Table and 
> hence know the location of foo even though it is out of scope? Or is 
> scope not just matter of knowing where to look?

$main:: does say to look in main's symbol table, *but* this only finds package
variables.  Variables declared with "my" are *lexical* variables and are only
available in the scope they are declared.

Thus (assuming we're in the main package):

	my $foo = 4;
	print $main::foo;   # undefined

will always discover $main::foo is undefined.  On the other hand:

	our $foo = 10;
	print $main::foo;   # prints "10"

works.  The use of "our" sets the variable as a package variable; that is one
which can be accessed by other packages and outside the scope in which it was
declared.  It's a global.... sort of.

An older way of achieving the same effect is:

	use vars $foo;
	$foo = 10;
	print $main::foo;   # prints "10"

but that's more rare to see now that most of the world has finally gotten around
to upgrading to Perl 5.6 or later.

Note that if I"m in the main package, and I have declared $foo already, then I
can just call it $foo without needing to fully qualify it.


   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |

More information about the Wellington-pm mailing list