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

前端 未结 9 1579
暖寄归人
暖寄归人 2021-02-10 02:14

Let\'s say I have a text file created using Data::Dumper, along the lines of:

my $x = [ { foo => \'bar\', asdf => undef }, 0, -4, [ [] ] ];
9条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 02:53

    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 = ; }
    my $x = eval $vars;
    

    Note that

    1. If you're bothering to put the assignment to $/ in its own block, you should use local to ensure it's value is actually restored at the end of the block; and
    2. The result of eval() needs to be assigned to $x.

提交回复
热议问题