Writing an anonymous sub in Perl to a file for later use

I have a Perl program that generates parsing rules as subtitles from an input file. Subjects are anonymously set to hash. Now, I want to export this hash, with all the subtitles, and then load them later to use them with another program.

How can I do it? Is there a way to extract the code for each auxiliary element, or can I copy the memory block that exists in the hash and then pass it as a hash when I load it later?

Thanks in advance.

+7
perl functional-programming hash generative-programming
source share
2 answers

From the "Code Links" in the Storable documentation (with additional emphasis):

Since Storable is version 2.05, CODE links can be serialized using B::Deparse . To enable this feature, set $Storable::Deparse to true. To enable deserialization, $Storable::Eval should be set to true. Remember that deserialization is done through eval , which is dangerous if the Storable file contains malicious data.

In the demo below, the child process creates a hash of anonymous subscribers. Then the parent element is a completely separate process and address space, so it cannot see %dispatch -reads output from freeze same way you can from a file on disk.

 #! /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; } 

Output:

  Hi!
 Holla!
 Yo! 
+2
source share

KiokuDB can handle storing code references in addition to other Perl types. So can various YAML modules, Data :: Dump :: Streamer and even Data :: Dumper.

+4
source share

All Articles