[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Package shadowing



Tim Ayers wrote:
> I am hoping someone will explain why the following program produces
> the warning
> 
>   "my" variable $a masks earlier declaration in same scope
>   at /home/tayers/pkg.pl line 11.
> 
> ----------------------- pkg.pl ----------------------------------
>   #!/usr/bin/perl -w
>   package foo;
>   my $a = 'foo';
>   sub foo { "foo::a=$a" }
>   package bar;
>   my $a = 'bar';
>   sub bar { "bar::a=$a" }
>   package main;
>   print foo::foo(), "   ", bar::bar(), "\n";
> ----------------------- pkg.pl ----------------------------------
> 
> The $foo::a and $bar::a variables are not available outside their
> respective package as far as I can tell. I assume the compiler keeps
> track of package switches. Why does it think I'm doing something
> worrisome?

i hope the following is right...

you're not doing anything with $foo::a or $bar::a.  these are
package variables, while my()ed variables are lexical variables,
not associated with a package (and not in the symbol table), but
rather with a lexical section of code.  lexical variables that are
declared outside of a block have "file scope": scope from their
declaration to the end of their file.  thus, the second my($a)
masks the earlier declaration.

here's a shorter example:

#!/usr/bin/perl -w

package foo;
my $a = 'foo';

package bar;
print "\$a is $a\n";

my $a = 'bar';
print "\$a is $a\n";
--
Steve Lane <sml@zfx.com>

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe