djberg96 has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

Perl 5.6.1 on Solaris 8

Given that I've slurped an OO package with a 'new' and 'init' method into a variable '$package', and the following code:

use Safe; my $sandbox = Safe->new;

I can do this:

$sandbox->reval("$package->new");

... or this ...

$sandbox->reval("$package->new->init");

But I can't figure out how to do this:

my $obj = $sandbox->reval("$package->new");
$sandbox->reval("$obj->init"); # Fails!
$sandbox->reval("$obj = $package->new; $obj->init"); # Fails!

I even tried reblessing '$obj' into '$package', but that didn't work.

Is what I'm trying to do even possible? Any suggestions?

Regards,

Mr. Sunblade

Replies are listed 'Best First'.
(tye)Re: Safe question
by tye (Sage) on Mar 22, 2002 at 16:06 UTC

    You are trying to eval code that looks like:     Your::Package=HASH(0xdeadbeef)->init which certainly won't work. The first case works since $package just contains a string so the resulting code is:     Your::Package->new You can't simply stringify an object and still have an object. And a package name is one of the very few things that you can simply stringify and get something that works as Perl source code.

    You could try just switching to single quotes, but I suspect that the sandbox won't have access to your lexical variables. But I don't know details about Safe, so I can't be much help here.

            - tye (but my friends call me "Tye")
      Oops. Actually, I meant to push out the single quote version. I had been mucking with double quotes last.

      I'm having an odd day as the error for the single quote version is not what I remember (it's now telling me $obj is undefined, even though I can clearly see that it *is* defined), and it now seems to work with no quotes just fine.

      Ok - time for a nap. :)

        $obj is defined in the calling code. That doesn't mean that it will be defined inside the sandbox. And doing "without quotes" also means that you are doing all of the work (and danger) outside of the sandbox and then just having the sandbox do eval on the results (which means you might as well not have the sandbox at all).

                - tye (but my friends call me "Tye")
Re: Safe question
by simon.proctor (Vicar) on Mar 22, 2002 at 19:00 UTC
    Someone else asked a similar question recently. Perhaps this node will help?