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

Greetings monks,

I can't seem to restore a object that was previously serialized. Do I need to re-bless?

Thanks for any help!!

Restoring :

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use SomeObject; #is this needed? local($/) = undef; open(D, "data.txt"); my $n = <D>; eval( Dumper($n) ); $n->show();
Saving object:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use SomeObject; my $n = SomeObject->new(datta => "foo", data2 => "foo2"); open(D, ">data.txt"); print D Data::Dumper::Dumper($n);

Replies are listed 'Best First'.
Re: Restore serialized objects
by GrandFather (Saint) on Mar 18, 2010 at 06:42 UTC

    Data::Dumper generates a little 'extra' code for you. Combining Chromatic's fix and removing the junk turns the trick:

    use strict; use warnings; use Data::Dumper; my $obj = bless {this => 1, that => 1}; my $fileStr; open my $out, '>', \$fileStr; (my $dumpData = Data::Dumper::Dumper($obj)) =~ s/^\$\w+\s*=\s*(bless\( +.*\))/$1/sm; print $out $dumpData; close $out; open my $in, '<', \$fileStr; my $str = do {local $/; <$in>}; close $in; my $newObj = eval $str; $obj->doIt (); $newObj->doIt (); sub doIt { my ($self) = @_; print "$self->{this} + $self->{that} = @{[$self->{this} + $self->{ +that}]}\n"; }

    Prints:

    1 + 1 = 2 1 + 1 = 2

    True laziness is hard work
Re: Restore serialized objects
by chromatic (Archbishop) on Mar 18, 2010 at 04:23 UTC
    my $n = <D>; eval( Dumper($n) ); $n->show();

    eval doesn't update $n in place here; it's still a plain string. Try:

    my $n = <D>; my $obj = eval $n; $obj->show();
      This is what I'm getting now:

      Can't call method "show" on an undefined value at ./test2 line 16, <D> chunk 1.

      I don't have to re-bless?