Object Reference

Joshua Keroes joshua_keroes at eli.net
Sat Jul 20 03:00:46 CDT 2002

You're making things too hard on yourself. Just require the file.

File: test.pl

  #!/usr/bin/perl -w
  use strict;

  our $VAR1;
  require "stored.pl";
  print $VAR1;


File: stored.pl
$VAR1 = [
            'foo' => 'bar',
            'baz' => 're',
            'qux' => 'quux'

That's all there is to it. The nice thing about using require() is 
that you'll get an error if there are compilation problems in the
data file.


PS Data::Dumper will let you name those variables using slightly
different syntax. Say you had two variables named $foo and $bar.
This method takes two arrayrefs. The first one contains the variables
you wish to dump. The second one contains the names of the variables.


  print Data::Dumper->Dump([$foo, $bar], ['foo', 'bar'])

If you need to dump arrays or hashes, be sure to pass refs instead.


  print Data::Dumper->Dump([\%hash, \@array], ['hash', 'array']);

PPS There are plenty of serialization methods to choose from. Here
are some that I've used:

1. Storable (freeze() / thaw() & store() / retrieve())

2. YAML (Dump() / Load())

3. XML::Simple (XMLout() / XMLin())


On (Fri, Jul 19 18:29), Jason White wrote:
> I'm using Data::Dumper to save and restore objects.
> Here is my RestoreFromFile function.
> sub RestoreFromFile($){
>         my ($filename,$tmp,$VAR1);
>         $filename=shift;
>         $tmp="";
>         open(INFILE, "$filename");
>         while(<INFILE>){
>                 $tmp.=$_;
>         }
>         eval $tmp;
>         return $VAR1; # returns a reference to an object
> # Why does Data::Dumper format the dump so nicely?  
> # I'm going to have to strip out all the newlines before writing to make this more useful
> }
> my $tmp = RestoreFromFile("objectfile");
> I now have a pointer to my object($tmp) but how do I typedef it or anothr variable to the right object type?
> $tmp->ObjectMethod() doesn't work, it thinks I'm trying to invoke a method of a scalar (the reference) not the object type.
> Jason White
> P.S.  There has to be a better serialization strategy, doesn't there?

More information about the Pdx-pm-list mailing list