Why is "$A::a" and "$a" diffrent ?

Discussion in 'Perl Misc' started by jh3an, Mar 14, 2008.

  1. jh3an

    jh3an Guest

    The following code doesn't make any sense, does it ?
    {
    package A;
    my $a = 3;
    if( ! ($a == $A::a) ){print "not equal\n"}
    }

    #output will be:
    not equal

    Why ? I think $A::a equals $a.
    If I do not use "my" operator, output will be the one as I expect.

    Does "my" operator do something in this case?




    Without my operator>>
    {
    package A;
    $a = 3;
    if(!($a == $A::a)){print "not equal\n"}
    else{ print "equal\n";}
    }

    #output:
    equal
     
    jh3an, Mar 14, 2008
    #1
    1. Advertising

  2. jh3an wrote:
    > The following code doesn't make any sense, does it ?


    Sure it does.

    > {
    > package A;
    > my $a = 3;
    > if( ! ($a == $A::a) ){print "not equal\n"}
    > }
    >
    > #output will be:
    > not equal
    >
    > Why ? I think $A::a equals $a.
    > If I do not use "my" operator, output will be the one as I expect.
    >
    > Does "my" operator do something in this case?


    It declares the lexically scoped variable $a, which is not the same
    variable as the package global $A::a.

    > Without my operator>>
    > {
    > package A;
    > $a = 3;
    > if(!($a == $A::a)){print "not equal\n"}
    > else{ print "equal\n";}
    > }
    >
    > #output:
    > equal


    In this example, $a is a package global, and $A::a is just the fully
    qualified name of the very same variable.

    --
    Gunnar Hjalmarsson
    Email: http://www.gunnar.cc/cgi-bin/contact.pl
     
    Gunnar Hjalmarsson, Mar 14, 2008
    #2
    1. Advertising

  3. jh3an <> wrote:
    > The following code doesn't make any sense, does it ?
    > {
    > package A;
    > my $a = 3;
    > if( ! ($a == $A::a) ){print "not equal\n"}
    > }
    >
    > #output will be:
    > not equal
    >
    > Why ? I think $A::a equals $a.



    "Coping with Scoping":

    http://perl.plover.com/FAQs/Namespaces.html


    --
    Tad McClellan
    email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"
     
    Tad J McClellan, Mar 14, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Abs
    Replies:
    0
    Views:
    518
  2. Joe Harrison
    Replies:
    1
    Views:
    360
    =?Utf-8?B?UmljaA==?=
    May 24, 2004
  3. Hardeep Rakhra
    Replies:
    8
    Views:
    460
    kchayka
    Apr 7, 2004
  4. Mr. SweatyFinger

    why why why why why

    Mr. SweatyFinger, Nov 28, 2006, in forum: ASP .Net
    Replies:
    4
    Views:
    912
    Mark Rae
    Dec 21, 2006
  5. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,004
    Smokey Grindel
    Dec 2, 2006
Loading...

Share This Page