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

First time using OO and storable together...

I don't seem to be able to: store($self); Now, I know $self is a ref to an object, but it *seems* like a hash...so I thought it would work. It seems to save OK, but on $self = restore(), $self isn't updated (it comes back as a hash, but then I can rebless it...but after I leave the function, the OLD $self comes back...)

I got around this by: store($self->{ALL}) and then I hang all of my key/values off the {ALL} leaf...

Is this the correct way ?

thanks

Replies are listed 'Best First'.
Re: storable $self
by chromatic (Archbishop) on May 21, 2002 at 03:32 UTC
    $self is probably not a reference to an object, unless you've done something like this:
    my $object = Class->new(); my $self = \$object;
    That's important, because you're doing nearly everything else right. Without seeing your code, I expect you may be doing something like this:
    $object->restore(); sub restore { my $self = shift; $self = restore(); }
    Unfortunately, since $self is declared as a lexical in the method and is shifted off of @_, the object is overwritten inside of the method with the restored code without updating the object itself.

    Possibly the best way around this is to return the new $self from the method. If you're concerned about interface purity, why not make a deserialization constructor? Another option is to take advantage of Perl's pass by reference semantics, operating directly on $_[0].

    sub deserialize { my $class = shift; return $class->restore(); } sub restore_me { $_[0] = $_[0]->restore(); }
Re: storable $self
by gav^ (Curate) on May 21, 2002 at 02:50 UTC
(tye)Re: storable $self
by tye (Sage) on May 21, 2002 at 15:17 UTC

    The first argument to a method call is a copy of the reference to the object. In

    my $obj; # ... $obj->Method();
    the call to Method() cannot change the caller's $obj.

    A more typical solution is to force the caller to use:     $obj= $obj->Restore(); to show that the object is being replaced.

            - tye (but my friends call me "Tye")