How to read back a file written using Data::Dumper (but not with the default VAR naming)?

StackOverflow https://stackoverflow.com/questions/19905163

  •  30-07-2022
  •  | 
  •  

質問

I have written a hash structure into a file using

print FILE Data::Dumper->Dump([$x], [ qw(*x) ]);

How do I read this back from file? If I use eval as shown in the following snippet, all I get is $VAR1 = undef;

local $/; $hash_ref = eval <FILE>;
役に立ちましたか?

解決

You can use the core module Storable to do this type of task.

use Storable;
store \%table, 'file';
$hashref = retrieve('file');

他のヒント

If those two statements are in the same file, then you can't do it that way unless you close the file handle and reopen the same file for reading. You could do something fancy like opening it with mode +> and then using seek to get back to the beginning before you read again, but why bother, especially since you already have a variable in the same program that contains the same data.

So I assume you are dumping the data from one program and reading it again in another. The problem with using Data::Dumper->Dump([$x], ['*x']) is that it will dereference $x and invent a variable of the appropriate type with the given name. So if $x is a hash reference it will name the variable %x, if it is an array reference then it will be @x etc.

It is far better to remove the star and just write Data::Dumper->Dump([$x], ['x']), which will avoid the dereferencing and name the variable $x.

To read the file back in you should just use do. Like this

use strict;
use warnings;

use Data::Dumper;

my $x = {
  a => 1,
  b => 2,
};

open my $fh, '>', 'dumper.txt' or die $!;
print $fh Data::Dumper->Dump([$x], ['x']);
close $fh;

my $data = do 'dumper.txt';

If you are constrained to using the form of Data::Dumper call that you show, then you must provide a variable of the appropriate type, like this

use strict;
use warnings;

use Data::Dumper;

my $x = {
  a => 1,
  b => 2,
};

open my $fh, '>', 'dumper.txt' or die $!;
print $fh Data::Dumper->Dump([$x], ['*x']);
close $fh;

my %data = do 'dumper.txt';

Note that, although the Data::Dumper output file refers to a variable %x, the file is run as a separate Perl program and there is no %x in the program that executes the do.

I tried several ways to export an existing hash. The only way I found that works is to create a new var that is a pointer to the existing hash. Then Borodin's answer works well.

use strict;
use warnings;

use Data::Dumper;

my %x = (
  a => 1,
  b => 2,
);

my $x = \%x;  # <<< Added so $x is a reference to %x.
open my $fh, '>', 'dumper.txt' or die $!;
print $fh Data::Dumper->Dump([$x], ['*x']);
close $fh;

my %data = do 'dumper.txt';
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top