【问题标题】:Safely test scalar for Storable compatibility安全地测试可存储兼容性的标量
【发布时间】:2012-03-16 08:57:54
【问题描述】:

我有一个接受 perl 数据结构的程序,该数据结构旨在成为可存储的标量。有没有办法测试标量是否是有效的 Storable 对象,如果不是,则不会死亡?

例如,如果我这样做:

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 Module?

【问题讨论】:

标签: perl


【解决方案1】:
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-ed,并且只有当我检查$@时才生效,内容如下:

$@= 'Global symbol "$i" requires explicit package name at (eval 24) line 1.
'

【讨论】:

    【解决方案2】:

    用魔法做到这一点:)

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2015-11-23
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2014-06-03
      相关资源
      最近更新 更多