[Wellington-pm] A question about scopes
Cliff Pratt
enkidu at cliffp.com
Tue Mar 28 13:01:18 PST 2006
Jacinta Richardson wrote:
> G'day Cliff,
>
> I don't know how useful you'd find it, but we cover scoping and scopes in our
> Introduction and Intermediate Perl course notes, available at
> http://perltraining.com.au/notes.html
>
> Scope itself is covered in the Intro Conditionals chapter, with further coverage
> when we get to Modules and Packages in the Intermediate course.
>
> Cliff Pratt wrote:
>
>>Say I have a Package and a PERL script.
>
>
> It's "Perl" typically. ;)
>
>
>>If the package uses a variable
>>$foo, and so does the script, I should be able to access the script's
>>version of $foo by $main::foo in the package. Am I correct?
>
>
> Consider the following case:
> ---------------------------------------------------
> #!/usr/bin/perl -w
> use strict;
>
> my $foo = 4; # $foo in the main package
> my $bar = 10; # $bar in the main package
>
> print "$foo\n"; # prints "4".
>
> if(1) {
> my $foo = 1; # $foo in the main package, but over-shadows previous
>
> $foo++;
>
> print "$foo\n"; # prints "2"
> }
>
> print "$foo\n"; # still prints "4"
>
>
> 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?
Cheers,
Cliff
--
http://barzoomian.blogspot.com
More information about the Wellington-pm
mailing list