perl-modperl mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Robert Landrum <>
Subject RE: [OT] Dynamically changing current package
Date Thu, 01 Feb 2001 23:27:05 GMT
You can also change the package using globs.

*{NewPackage::} = *{TestPackage::};

NewPackage will then contain all things in TestPackage....

Then you can redefined everything in TestPackage without affecting 
anything in NewPackage.

You can also do something like

for my $name (keys %{Test::}) {
    *{"NewPackage::".$name} = *{"Test::".$name} if($name =~ /somefunc/);

That's a poor mans export....

You can also load different modules based on developer if you force 
them to log in and create packages preceeded by their usernames....

$user = $r->connection->user; # right?
$usrpkg = $user."::Foo::";
*{original::Foo::} = *{Foo::} unless(defined *{original::Foo::});

*{Foo::} = (defined *{$usrpkg}) ? *{$usrpkg} : *{original::Foo::};
# in case another user has already loader their stuff over top of Foo.

That should make life interesting... I've never actually tried any of 
this, I'm just spitting out some ideas...

Robert Landrum

At 12:34 PM -0500 2/1/01, wrote:
> > Andrew Ho <> 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. 

View raw message