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

I'm using Safe, and I can get it to work just fine, until I try to do one thing... share $self, then use it in some code to be reval'd, it gives me uninitialized value at (eval 2) line 1. Any ideas? I've scoured the archives and begged in irc channels (and read the docs until my eyes were bloodshot)

Replies are listed 'Best First'.
Re: safe and $self
by djantzen (Priest) on Nov 26, 2002 at 05:48 UTC

    From the Safe docs for share(NAME, ...): Each NAME must be the name of a non-lexical variable, typically with the leading type identifier included.

    Since in OO Perl the current instance of a package is referred to merely by a lexical variable declared within a subroutine, i.e., my $this = shift(@_), sharing it will not be possible. You're seeing 'uninitialized' warnings now because Safe attempts to look up $SamplePackage::self, which is uninitialized.

    If you're truly desperate you could effectively make your class instance a public static member using our, and then share that reference. But that's generally a bad idea unless you're sure your instance will always be a singleton.

      I finally signed up for an account (instead of just lurking), so I'm the anonymous monk that posted this node. the code I have is:
      sub codewrapper { my $self = shift; $self->{code}->share('$self'); $self->{code}->share('$test'); $code=$_[0]; $self->{code}->reval($code); $test->{code}->reval($code); }
      $test is the test object, and that gives the same error, it is declared with my $test = ..., but outside of any subs. neither work, both produce eval errors.
        I think, like what fever said, that you've painted yourself in to a corner with this. $self is a lexical variable, in other words, it doesn't really exist outside of the codewrapper function, those seven lines.

        The real problem is if you are ever calling the codewrapper function within itself. Then you're going to have trouble sharing the correct $self since there will, at that point, be two of them.

        The solution might be to not use Safe at all. It might be best to re-engineer your application, since using eval, and presumably reval are much slower than the alternatives.

        If this isn't going to work, then what you're probably going to have to do is create separate compartments for each object. I'm not sure if there's an easy way to do this or not.
Re: safe and $self
by tadman (Prior) on Nov 26, 2002 at 05:36 UTC
    If you could post a smidgen of code that might serve as a test case, that would really help. Safe can do all kinds of things, so seeing how you're using it is important.