gpt4 book ai didi

perl - 在 Perl 中,如何保存包含子例程引用的散列?

转载 作者:行者123 更新时间:2023-12-02 06:20:08 24 4
gpt4 key购买 nike

正如标题所说,在 Perl 中,如何保存包含子程序引用列表的散列?例如,我有以下散列,其中包含对其他库中包含的子例程的引用:

my %testMap = (
helloTest => \&runHello,
goodbyeTest => \&runGoodbye,
);

当我尝试使用 Data::Dumper 时在以下事项中:

my($out) = new FileHandle ">$fileName"; 
my $serialized => Data::Dumper->Dump([\%testMap], [$HASH_REFERENCE]);
print $out $serialized;
close $out;

我最终得到一个如下所示的文件:

$testMap = {
'goodbyeTest' => sub { "DUMMY" },
'helloTest' => sub { "DUMMY" }
};

当我希望输出看起来像原始列表中出现的那样时,有没有办法做到这一点?

Data::Dumper 和 Storable 的一些实验到目前为止没有任何结果,我怀疑这是由于引用的实际代码对正在运行的代码不可用。

最佳答案

Storable自 2.05 版以来已经能够序列化 coderefs。

use strict;
use warnings;
use Storable;
use Data::Dump 'dump';

{
no warnings; # Suppress 'used only once' warning
$Storable::Deparse = 1; # Needs to be set to true as per docs
$Storable::Eval = 1; # Same as above
}

sub hello_world { print "Hello world!\n" }

my %hash = (
helloTest => \&hello_world,
byeTest => sub { print "Goodbye!\n" },
);

store \%hash, 'file'; # Could use freeze/thaw for
my $cloned = retrieve( 'file' ); # in-memory serialization

$cloned->{helloTest}(); # Prints 'Hello world!'

关于perl - 在 Perl 中,如何保存包含子例程引用的散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12502232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com