我的目标是将字符串读回到数组引用中。
我修改了这里的示例代码。该网站上的示例使用哈希,在我的例子中我想使用数组。这是我尝试过的:
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};
Run Code Online (Sandbox Code Playgroud)
运行此代码会产生此错误:
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
Run Code Online (Sandbox Code Playgroud)
如果删除该use strict;编译指示,错误就会消失,并且我会得到预期的数组。
从转储器输出获取数组变量的正确方法是什么?
您应该$@在任何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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
957 次 |
| 最近记录: |