develooper Front page | perl.perl5.porters | Postings from November 1999

lexicals penetrating do 'b'?

From:
Barrie Slaymaker
Date:
November 27, 1999 20:45
Subject:
lexicals penetrating do 'b'?
Message ID:
199911280456.XAA12826@jester.slaysys.com
I was confused to see this:

   [barries@jester safari]$ perl a
   A, main, , SCALAR(0x80d0b90)?SCALAR(0x80d0b48)
   B, ABCD, ABCD's context, SCALAR(0x80d0b48)?SCALAR(0x80d0b48)
   C, main, , SCALAR(0x80d0b90)?SCALAR(0x80d0b48)
   D, ABCD, ABCD's context, SCALAR(0x80d0b48)?SCALAR(0x80d0b48)

   A, main, MNOP's context, SCALAR(0x80cd1a4)?SCALAR(0x80d0b48)
   B, ABCD, MNOP's context, SCALAR(0x80cd1a4)?SCALAR(0x80d0b48)
   C, main, MNOP's context, SCALAR(0x80cd1a4)?SCALAR(0x80d0b48)
   D, ABCD, MNOP's context, SCALAR(0x80cd1a4)?SCALAR(0x80d0b48)

Given files a:

   package MNOP ;

   my $context = "MNOP's context" ;

   sub read_config {
      do 'b' ;
   }

   do 'b' ;
   print "\n" ;
   read_config ;

and b:

   BEGIN {
      $ABCD::context = "ABCD's context" ;
      print join( ", ", "A", __PACKAGE__ , $context, \$context . "?" . \$ABCD::context ), "\n" ;
   }

   print join( ", ", "C", __PACKAGE__ , $context, \$context . "?" . \$ABCD::context ), "\n" ;

   package ABCD ;

   BEGIN {
      print join( ", ", "B", __PACKAGE__ , $context, \$context . "?" . \$ABCD::context ), "\n" ;
   }

   print join( ", ", "D", __PACKAGE__ , $context, \$context . "?" . \$ABCD::context ), "\n" ;

It seems like the "my $context" in 'a' is being seen in the do that's
called from read_config(), but not the other one.

It also seems that there's some vagueness in the documentation, since
__PACKAGE__ reports "main" initially, and not "MNOP", yet perlmod
says that evaled strings execute in the package they were compiled
in and perlfunc says that do is like scalar eval `cat b`.  This
led me to expect __PACKAGE__ to be 'MNOP', not 'main'.

FWIW, changing a to:

   package MNOP ;

   my $context = "MNOP's context" ;

   sub read_config {
      scalar eval `cat b` ;
   }

   scalar eval `cat b` ;
   print "\n" ;
   read_config ;

I get:

   A, main, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)
   B, ABCD, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)
   C, main, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)
   D, ABCD, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)

   A, main, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)
   B, ABCD, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)
   C, main, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)
   D, ABCD, MNOP's context, SCALAR(0x80cd22c)?SCALAR(0x80d0ed4)

in which the __PACKAGE__ still surprises me, but the scoping does
not.

_03 and _61 both behave this way.

- Barrie



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About