[sf-perl] dynamic use command

Joe Brenner doom at kzsu.stanford.edu
Fri Apr 4 19:26:04 PDT 2008


Randy J. Ray <rjray at blackperl.com> wrote:

> > So, will eval have the module loaded outside the eval?
> > Or will I have to require it "for real"?
> >
> > I thought eval was a sandbox of sorts.
>
> No, it merely prevents a fatal error from stopping the program (instead, the
> error message is saved in the special variable, $@). The code is loaded, and
> any exporting it does is to the package-space in which the eval was called.

Yes, that's right.  And if you like you can import symbols into any
arbitrary package, by re-opening it with another "package" statement.

I've been known to do things like this:

  sub dynamic_use {
     my $module = shift;

     my $calling_namespace = caller(0);
     $eval_code =
       "package $calling_namespace; " .
       "require $module; "            .
       "import  $module;" ;

     eval $eval_code;

     if ($@) {
       return 0;
     } else {
       return 1;
     }
  }




More information about the SanFrancisco-pm mailing list