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

前端 未结 9 1581
暖寄归人
暖寄归人 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条回答
  • 2021-02-10 02:58

    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

    $Data::Dumper::Purity = 1;
    

    or

    $obj->Purity(1);
    

    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.

    0 讨论(0)
  • 2021-02-10 02:58

    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;
    
    0 讨论(0)
  • 2021-02-10 03:03

    I think you want to put

    our $x;
    

    into your code before accessing x. That will satisfy the strict error checking.

    That being said, I join the other voices in suggesting Storable.

    0 讨论(0)
提交回复
热议问题