Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Packages, scope, and lexical variables.

by ikegami (Patriarch)
on Mar 08, 2005 at 07:15 UTC ( [id://437436]=note: print w/replies, xml ) Need Help??


in reply to Packages, scope, and lexical variables

The output seems to indicate that a lexical variable (i.e. $var) is not associated with package level scope.

Correct. By definition, lexicals are block scoped and in no way related to packages. The file is considered a block for this purpose.

If you want $Test::var to work, change my to our, making $var a package variable instead of a lexical.

Furthermore, there doesn't appear to be any way to prevent an interloper from creating subroutines within the namespace of neighboring (or distant) packages.

That's true, but I haven't known this to be a problem. Any of the following three lines of code would create a sub named new_sub in the package Test, no matter which file contained the code.

{ package Test; sub new_sub { ... } } -or- sub Test::new_sub { ... } -or- *Test::new_sub = sub { ... };

Replies are listed 'Best First'.
Re^2: Packages, scope, and lexical variables.
by ysth (Canon) on Mar 08, 2005 at 08:54 UTC
    Any of the following three lines of code would create a sub named new_sub in the package Test, no matter which file contained the code.
    Ah, but only the one with a package statement will necessarily use Test as the package for finding unqualified global variables. One-arg bless, caller() in called routines, and SUPER:: also will be affected, as well as probably other things that I'm unable to think of ATM. For all but trivial routines, using a proper package statement is best.

    The following demonstrates how Nopkg::Super is connected to it's containing package "Pkg", not to "Nopkg":

    $ cat pkg.pl use strict; use warnings; sub main::Duper { print "in main::Duper, called from pkg", scalar caller, "\n"; } @Pkg::ISA = "Super"; @Nopkg::ISA = "main"; sub Super::Duper { print "in Super::Duper, called from pkg ", scalar caller, "\n"; } { package Pkg; sub Nopkg::Duper { our @ISA; print "isa: @ISA\n"; my $obj = bless {}; print "blessed a ", ref($obj), "\n"; $obj->SUPER::Duper; } } Nopkg::Duper(); sthoenna@DHX98431 ~/pbed $ perl pkg.pl isa: Super blessed a Pkg in Super::Duper, called from pkg Pkg
      True. Thanks for eloborating.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://437436]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-25 05:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found