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?
答案 0 :(得分:4)
You need to pass an array reference to Dumper rather than the array itself, i.e.:
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.
答案 1 :(得分:3)
在意外失败的任何$@
之后,您应该检查eval
。
默认情况下,Dumper
输出将以$VAR1 = ...
开头。如果您尚未在当前范围内声明$VAR1
,则在use strict
下,您的Dumper
输出将无法编译,$@
将包含可怕的Global symbol $VAR1 requires explicit package ...
消息。
因此,如果您使用strict
并在eval
输出时调用Dumper
,请声明$VAR1
。
my $VAR1;
my $array_ref = eval($output_string);
die $@ unless $array_ref;