我有一个Perl程序,它从输入文件生成解析规则作为subs. sub是匿名定义的一个放入哈希.现在,我想导出该哈希,包含所有的子,然后再次加载它们以与其他程序一起使用.
我该怎么做呢?有没有办法提取每个子代码,或者我可以复制散列存在的内存块,然后在我稍后再次加载时将其转换为哈希值?
提前致谢.
解决方法
从Storable文档的
“Code References”部分(更加强调):
Since Storable version 2.05,CODE references may be serialized with the help of
B::Deparse
. To enable this feature,set$Storable::Deparse
to a true value. To enable deserialization,$Storable::Eval
should be set to a true value. Be aware that deserialization is done througheval
,which is dangerous if the Storable file contains malicIoUs data.
在下面的演示中,子进程创建匿名subs的哈希.然后父进程在一个完全独立的进程和地址空间中,因此它无法看到%dispatch-以与磁盘上文件相同的方式从冻结中读取输出.
#! /usr/bin/perl use warnings; use strict; use Storable qw/ freeze thaw /; my $pid = open my $fh,"-|"; die "$0: fork: $!" unless defined $pid; if ($pid == 0) { # child process my %dispatch = ( foo => sub { print "Yo!\n" },bar => sub { print "Hi!\n" },baz => sub { print "Holla!\n" },); local $Storable::Deparse = 1 || $Storable::Deparse; binmode STDOUT,":bytes"; print freeze \%dispatch; exit 0; } else { # parent process local $/; binmode $fh,":bytes"; my $frozen = <$fh>; local $Storable::Eval = 1 || $Storable::Eval; my $d = thaw $frozen; $d->{$_}() for keys %$d; }
输出:
Hi! Holla! Yo!