amw1 has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to have variables inside of a coderef evaluated before Storable stores them? i.e. these chunks of code

store_create.pl
use Storable; use strict; my $x = 10; my $coderef = sub { print "\nx is: $x\n"; }; $Storable::Deparse = 1; Storable::nstore($coderef, 'frozen_ref');
store_retrieve.pl
use Storable; use strict; $Storable::Eval = 1; my $coderef = Storable::retrieve('frozen_ref'); &$coderef();
I think what I'm looking for is a way to store a lexical closure but I'm not 100% sure of the terminology.
The store_retrieve.pl executes the code but $x is undef, I'm looking for a way to have it be 10.

Replies are listed 'Best First'.
Re: coderefs and storable
by kvale (Monsignor) on Mar 12, 2004 at 18:53 UTC
    Here is an example of a closure in your case:
    my $coderef; { my $x = 10; $coderef = sub { print "\nx is: $x\n"; }; }

    -Mark

      Alternatively ...
      my $coderef = do { my $x = 10; sub { print "\nx is : $x\n"; }; };

      ------
      We are the carpenters and bricklayers of the Information Age.

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

        ultimately what I'm trying to do is to insert an action (as a serialized code ref) into a database to be run at a later time. $x will need to change for different instances of the coderef. Something like. . . . (pseudo code)
        sub RemoveThing { my $thingid = shift(); # QueueAction serializes it's first argument QueueAction(\&Handlers::thing_remove()) } package Handlers; sub thing_remove { database foo to remove $thingid; }
        I know I can make QueueAction take an argument list for passing to the serialized subroutine. Just trying to avoid it.
Re: coderefs and storable
by diotalevi (Canon) on Mar 12, 2004 at 19:15 UTC
    You'll be wanting lisp. Paul Graham wrote something doing just this. Closures are not serializable. Code refs, maybe.
      I'm hearing that more and more. My boss is quite fond of lisp and in talking to him I'm becoming quite fond of it. I need to spend some time and learn the language.