简体   繁体   中英

Perl: Read/Reverse Data Dumper back into an array

My goal is to read a string back into an array ref.

I modified the example code here . The example on that site uses a Hash and in my case I want to use an Array. Here is what I tried:

use strict;
use warnings;

# Build an array with a hash inside
my @test_array = ();
my %test_hash = ();
$test_hash{'ding'} = 'dong';
push @test_array, \%test_hash;

# Get the Dumper output as a string
my $output_string = Dumper(\@test_array);

# eval_result should be an array but is undef
my @eval_result = @{eval $output_string};

Running this code produces this error:

Can't use an undefined value as an ARRAY reference at
        /var/tmp/test_dumper.pl line 30 (#1)
    (F) A value used as either a hard reference or a symbolic reference must
    be a defined value.  This helps to delurk some insidious errors.

Uncaught exception from user code:
        Can't use an undefined value as an ARRAY reference at /var/tmp/test_dumper.pl line 30.
 at /var/tmp/test_dumper.pl line 30.
        main::test_array_dump() called at /var/tmp/test_dumper.pl line 14

If I remove the use strict; pragma, the error goes away and I get the expected array.

What is the correct way to get an array variable from a Dumper output?

You need to pass an array reference to Dumper rather than the array itself, ie:

my $output_string = Dumper(\@test_array);

The following works for me:

my $output_string = Dumper(\@test_array);

# eval_result should be an Array but is undef
my @eval_result = @{eval $output_string};
print Dumper(\@eval_result);

results in:

$VAR1 = [
    {
        'ding' => 'dong'
    }
];

See also examples in Dumper documentation .

You should be checking $@ after any eval that unexpectedly fails.

The Dumper output by default will begin with $VAR1 = ... . If you have not declared $VAR1 in the current scope, then under use strict your Dumper output will fail to compile and $@ will contain the dreaded Global symbol $VAR1 requires explicit package ... message.

So if you are using strict and calling eval on Dumper output, declare $VAR1 .

my $VAR1;
my $array_ref = eval($output_string);
die $@ unless $array_ref;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM