How can I serialize closure in Perl?

I think this is best asked using an example:

use strict; use warnings; use 5.010; use Storable qw(nstore retrieve); local $Storable::Deparse = 1; local $Storable::Eval = 1; sub sub_generator { my ($x) = @_; return sub { my ($y) = @_; return $x + $y; }; } my $sub = sub_generator(1000); say $sub->(1); # gives 1001 nstore( $sub, "/tmp/sub.store" ); $sub = retrieve("/tmp/sub.store"); say $sub->(1); # gives 1 

When I reset /tmp/sub.store , I see:

 $VAR1 = sub { package Storable; use warnings; use strict 'refs'; my($y) = @_; return $x + $y; } 

But $x never defined in this subclause. I would expect that the sub-generation expressed by sub_generator will replace $x with its actual value after generation. How do i solve this?

Please note that this question applies to this one .

+6
function closures serialization perl store
source share
1 answer

Unfortunately, I don't think Storable works with closure. However, there are other CPAN modules that will serialize the closure. E.g. Data::Dump::Streamer

 use 5.012; use warnings; use Data::Dump::Streamer; sub sub_generator { my ($x) = @_; return sub { my ($y) = @_; return $x + $y; }; } my $sub = sub_generator(1000); say $sub->(1); # gives 1001 my $serialised = Dump( $sub )->Out; my $copy = do { my $CODE1 = undef; eval $serialised; $CODE1; }; say $copy->(2); # gives 1002 say $sub->(1); # still gives 1001 

Here's what the serialized code looks like when printing here say Dump $sub; :

 my ($x); $x = 1000; $CODE1 = sub { use warnings; use strict 'refs'; BEGIN { $^H{'feature_unicode'} = q(1); $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } my($y) = @_; return $x + $y; }; 


Update

See this topic Storage and closure on the Perl5 mailing list. He confirms that I was thinking about Storable and closing.

/ I3az /

+5
source share

All Articles