Let\'s say I have a text file created using Data::Dumper, along the lines of:
my $x = [ { foo => \'bar\', asdf => undef }, 0, -4, [ [] ] ];
This works fine for me:
Writing out:
open(my $C, qw{>}, $userdatafile) or croak "$userdatafile: $!";
use Data::Dumper;
print $C Data::Dumper->Dump([\%document], [qw(*document)]);
close($C) || croak "$userdatafile: $!";
Reading in:
open(my $C, qw{<}, $userdatafile) or croak "$userdatafile: $!";
local $/ = $/;
my $str = <$C>;
close($C) || croak "$userdatafile: $!";
eval { $str };
croak $@ if $@;
Are you sure that file was created by Data::Dumper? There shouldn't be a my
in there.
Some other options are Storable, YAML, or DBM::Deep. I go through some examples in the "Persistence" chapter of Mastering Perl.
Good luck, :)
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);
This snippet is short and worked for me (I was reading in an array). It takes the filename from the first script argument.
# Load in the Dumper'ed library data structure and eval it
my $dsname = $ARGV[0];
my @lib = do "$dsname";
If you want to stay with something easy and human-readable, simply use the Data::Dump module instead of Data::Dumper
. Basically, it is Data::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:
my $x = [ { foo => 'bar', asdf => undef }, 0, -4, [ [] ] ];
Save it using:
use Data::Dump "pp";
open F, ">dump.txt";
print F pp($x);
This produces a file dump.txt
that looks like (on my PC at least):
[{ asdf => undef, foo => "bar" }, 0, -4, [[]]]
Load it using:
open F, "dump.txt";
my $vars;
{ local $/ = undef; $vars = <F>; }
my $x = eval $vars;
Note that
$/
in its own block, you should use local
to ensure it's value is actually restored at the end of the block; andeval()
needs to be assigned to $x
.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.