perl-modperl mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mgra...@circadence.ca
Subject RE: [OT] Dynamically changing current package
Date Thu, 01 Feb 2001 17:34:19 GMT


> Andrew Ho <andrew@tellme.com> wrote:
> I know how to use "package" in the normal case, where it's static.
> However, you can't say "package $foo" or even "eval 'package 
> foo'" or even "BEGIN { eval 'package foo' }." I'm wondering 
> if there's any way short of hacking the Perl source itself 
> to make the compiler dynamically choose a namespace.

The reason your eval examples don't work is because the scope of the package
declaration only extends to the end of the current block, the end of the
current file, or the end of the current 'eval', whichever comes first.

If you want to put code into a particular package at runtime, you have to
recompile that code along with the package declaration:

    eval "
        package $foo;
        $scalar_containing_some_code
    ";

Or you can pull in the code from an external file:
   
    eval "
        package $foo;
        do '$script';
    ";

The package declaration is scoped the way it is is because it is a
compile-time directive, not a run-time directive.  Code is placed into a
particular package at compile-time; to change the package of a particular
piece of code at run-time really means to destroy that compiled code and to
recompile it in a new package.  This is essentially what happens when you
use the string form of eval, above.  


Michael


Mime
View raw message