How should I serialize code links in Perl?

I want an nstore hash of a Perl file that also contains a link to the code. After this perldoc, I wrote something like this:

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

I get a warning Name "Storable::Deparse" used only once: possible typo at test4.pl line 15. .. I think I could specifically suppress this warning, but it makes me wonder if I am not doing something wrong.

Please note that this question applies to this one . Various names to distinguish them will be most welcome.

+2
function serialization perl store
source share
3 answers

You did not consider loading the storage module before setting one of its configuration values.

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

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

When serializing such elements, you must describe them in such a way that they can be recreated. For example, you can serialize a file descriptor as a path and an offset or a code link as the name of the function referenced by the link.

You can find the name of the routine referenced by the code points 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 that you cannot serialize anonymous links, and serialized data can only be reliably used by programs that implement named functions in the same way.

If you need to do this, you are probably better off using a class instead of just referencing the code.

+1
source share

You also need to install

 $Storable::Eval = 1; 

in the following way:

 #! 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}(); 
0
source share

All Articles