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

Re: [FWP] Package shadowing



Tim Ayers <tayers@bridge.com> writes:

> Hi all,
> 
> 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?

`my' variables don't live in packages, they live in scopes!  So your
second definition of $a masks your first.  You're *not* defining
$foo::a and $bar::a as you might think.

This will illustrate some more:

    #!/usr/local/bin/perl -w

    # Some package/my scope worrisome thingies...

    my $a = 11;

    package Foo;
    sub foo { print "a is $a\n"; }

    package Bar;
    sub bar { print "a is $a\n"; }

    package main;
    print "a is $a\n";
    Foo::foo;
    Bar::bar;

-- 
Ariel Scolnicov        |"GCAAGAATTGAACTGTAG"            | ariels@compugen.co.il
Compugen Ltd.          |Tel: +972-2-5713025 (Jerusalem)	\ We recycle all our Hz
72 Pinhas Rosen St.    |Tel: +972-3-7658117 (Main office)`---------------------
Tel-Aviv 69512, ISRAEL |Fax: +972-3-7658555    http://3w.compugen.co.il/~ariels

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