How should I serialize code references in Perl?

被刻印的时光 ゝ 提交于 2019-12-06 07:53:36

You have neglected to load the Storable module, before setting one of its config values.

use strict;
use warnings;
use Storable qw(nstore);
local $Storable::Deparse = 1; 
my %hash = (... CODE => ...);
nstore (\%hash, $file);

Code references cannot be simply serialized. File handles, database connections, and anything that has external resources cannot be simply serialized.

When serializing such items, you must describe them in such a way that they can be recreated. For instance, you might serialize a file handle as a path and an offset or a code reference as the name of function the reference was pointing to.

You can find the name of the subroutine a code reference points to with Sub::Identify:

#!/usr/bin/perl

use strict;
use warnings;

use Sub::Identify qw/sub_fullname/;

sub foo {}

my $r = \&foo;

print sub_fullname($r), "\n";

Of course, this means you cannot serialize anonymous references and the serialized data can only reliably be used by programs that implement the named functions in the same way.

If you find yourself needing to do this, you are probably better off using a class instead of a simple code reference.

You also need to set

$Storable::Eval = 1;

thus:

#! perl

use strict;
use warnings;

use Storable qw /nstore retrieve/;


local $Storable::Deparse = 1; 
local $Storable::Eval = 1; 

my %hash = ( CODE => sub {print "ahoj\n";});


nstore (\%hash, 'test');
my $retrieved = retrieve ( 'test');

$retrieved->{CODE}();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!