我有一个接受perl数据结构的程序,该结构旨在成为一个可存储的标量。有没有办法测试标量是否是有效的可存储对象,如果不存在则不会死亡?
例如,如果我这样做:
use Storable qw(freeze thaw);
my $ref = thaw("lol_not_storable")
我在/usr/local/lib/perl/5.12.4/Storable.pm第420行,在test.pl第5行找回“可存储的二进制图像v54.111比我更新(v2.8)”
我想弄清楚是否可以在没有eval的情况下干净地处理这些异常。是否可以不重写Storable Perl模块?
答案 0 :(得分:3)
eval { thaw("lol_not_storable"); };
与
不同eval qq/thaw("lol_not_storable");/;
因为Perl有足够的机会解析第一个,但是等待解析第二个。请注意,下面是编译错误:
use 5.014;
use strict;
use warnings;
say 'Would print without compile error';
eval { $i++; };
^D
Global symbol "$i" requires explicit package name at - line 8.
Execution of - aborted due to compilation errors.
而eval '$i++'
不会。我认为你所听到的大多数关于eval
的沮丧更多的是后者,而不是前者。后者将字符串计算为代码,前者主要告诉Perl“不要死”。
这是字符串版本:
use 5.014;
use strict;
use warnings;
say 'Would print without compile error';
eval ' $i++;';
输出:
Would print without compile error
代码仍然无法编译,但只有在eval
编辑时才会编译,并且只有在我选中$@
时才会生效:
$@= 'Global symbol "$i" requires explicit package name at (eval 24) line 1.
'
答案 1 :(得分:0)
用魔法做到:)
use Data::Dumper;
use Storable qw(freeze thaw read_magic);
my $storable_str = freeze( [ 1 .. 42 ] );
print Dumper( read_magic($storable_str) );
# prints:
# $VAR1 = {
# 'netorder' => 0,
# 'hdrsize' => 15,
# 'version' => '2.7',
# 'minor' => 7,
# 'longsize' => 8,
# 'ptrsize' => 8,
# 'version_nv' => '2.007',
# 'byteorder' => '12345678',
# 'major' => 2,
# 'intsize' => 4,
# 'nvsize' => 8
# };
my $ordinary_str = join( ',', (1 .. 42) );
print Dumper( read_magic($ordinary_str) );
# prints:
# $VAR1 = undef;
# So:
if(read_magic($something_to_check)){
my $ref = thaw($something_to_check);
}else{
# foo
}