Let's say I have a text file created using Data::Dumper
, along the lines of:
my $x = [ { foo => 'bar', asdf => undef }, 0, -4, [ [] ] ];
I'd like to read that file back in and get $x
back. I tried this:
my $vars;
{
undef $/;
$vars = <FILE>;
}
eval $vars;
But it didn't seem to work -- $x
not only isn't defined, when I try to use it I get a warning that
Global symbol $x requires explicit package name.
What's the right way to do this? (And yes, I know it's ugly. It's a quick utility script, not e.g., a life-support system.)
Here's a thread that provides a couple different options: Undumper
If you're just looking for data persistence the Storable module might be your best bet.
By default, Data::Dumper output cannot be parsed by eval, especially if the data structure being dumped is circular in some way. However, you can set
or
where
obj
is a Data::Dumper object. Either of these will cause Data::Dumper to produce output that can be parsed by eval.See the Data::Dumper documenatation at CPAN for all the details.
This snippet is short and worked for me (I was reading in an array). It takes the filename from the first script argument.
As others have already said, you'd probably be better off storing the data in a better serialisation format:
Personally, I think I'd aim for YAML or JSON... you can't get much easier than:
my $data = YAML::Any::LoadFile($filename);
If you want to stay with something easy and human-readable, simply use the
Data::Dump
module instead ofData::Dumper
. Basically, it isData::Dumper
done right -- it produces valid Perl expressions ready for assignment, without creating all those weird$VAR1
,$VAR2
etc. variables.Then, if your code looks like:
Save it using:
This produces a file
dump.txt
that looks like (on my PC at least):Load it using:
Note that
$/
in its own block, you should uselocal
to ensure it's value is actually restored at the end of the block; andeval()
needs to be assigned to$x
.I think you want to put
into your code before accessing x. That will satisfy the strict error checking.
That being said, I join the other voices in suggesting Storable.