How do I read back in the output of Data::Dumper?

2019-03-20 21:00发布

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.)

9条回答
祖国的老花朵
2楼-- · 2019-03-20 21:25

As Rich says, you probably don't want to use Data::Dumper for persistence, but rather something like Storable.

However, to answer the question asked... IIRC, Data::Dumper doesn't declare your variables to be my, so are you doing that yourself somehow?

To be able to eval the data back in, the variable needs to not be my within the eval. If your text file contained this:

$x = [ { foo => 'bar', asdf => undef }, 0, -4, [ [] ] ];

Then this would work:

my $vars;
{
  undef $/;
  $vars = <FILE>;
}

my $x;    
eval $vars;
print $x;
查看更多
Deceive 欺骗
3楼-- · 2019-03-20 21:26

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 $@;
查看更多
做自己的国王
4楼-- · 2019-03-20 21:31

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, :)

查看更多
登录 后发表回答