Perl:将数据转储程序读回数组
我的目标是将字符串读回数组ref 我修改了示例代码。该站点上的示例使用散列,在我的示例中,我希望使用数组。以下是我尝试过的:Perl:将数据转储程序读回数组,perl,Perl,我的目标是将字符串读回数组ref 我修改了示例代码。该站点上的示例使用散列,在我的示例中,我希望使用数组。以下是我尝试过的: 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 outpu
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};
运行此代码会产生以下错误:
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
如果我删除使用strict代码>pragma,错误消失,我得到了预期的数组
从转储程序输出中获取数组变量的正确方法是什么?您需要将数组引用传递给转储程序,而不是数组本身,即:
my $output_string = Dumper(\@test_array);
以下是我的作品:
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);
结果:
$VAR1 = [
{
'ding' => 'dong'
}
];
另请参见中的示例。您应该在任何意外失败的eval
之后检查$@
默认情况下,转储程序
输出将以$VAR1=…
开头。如果您尚未在当前范围内声明$VAR1
,则在使用strict
下,您的转储程序
输出将无法编译,$@
将包含可怕的全局符号$VAR1需要显式包…
消息
因此,如果使用strict
并在Dumper
输出上调用eval
,请声明$VAR1
my $VAR1;
my $array_ref = eval($output_string);
die $@ unless $array_ref;
谢谢@swornabsent。如果另一个应用程序(转储数组而不是ref)给了我一个字符串,有没有办法将字符串读回数组?@DirtyPenguin这可能是一个挑战,我不确定是否有一种硬性的方法或一个模块可以立即执行。我认为你所要做的就是写一些东西来去掉前面的$VAR2..$VAR\u n_
字符串并用方括号括起来,这应该是可行的。很抱歉,我无法为您指出一些快速简单的内容。我更新了代码以转储数组引用。但当我尝试求值该字符串时,仍然会得到一个undef。有什么想法吗?@DirtyPenguin你可以保留数组赋值。我在我的答案中编辑了适合我的代码。当我删除use strict代码>布拉格。我已经更新了这个问题。如何使其与一起工作,请使用strict代码>?就是这样。谢谢。使用JSON之类的东西而不是转储程序输出可能是值得的。