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

Hello fellow monks,

I have run into an issue there are lots of ways around, but those aren't as interesting as the issue itself. I'd like to store subroutines somewhere out of process and later retrieve them for invokation.

Storing the source of the routines and running them through eval later is trivial, but I'd like to store the binary object that the CODE ref points to. I know that this could be much more brittle, not guaranteed to work between Perl versions and host platforms for instance. Nevertheless I'd like to know how to do it.

The modules Storable, FreezeThaw and Data::Dumper all choke (or cheat) on CODE refs. Is this because it can't be done, or just because it shouldn't?

Thanks for your thoughts and if this node is a dupe, please excuse my poor search-fu.

Replies are listed 'Best First'.
Re: Serializing code refs
by ysth (Canon) on Feb 25, 2005 at 06:08 UTC
    I believe what you want would require some modifications to the highly experimental B::Bytecode. That module was originally intended to allow saving and later loading compiled versions of scripts or modules for efficiency. AIUI, it turned out that perl's code structure is so verbose (since it really wasn't designed with this in mind), that the costs to read in saved bytecode exceed what it takes to read and compile in the first place.

    I'd encourage you to use Data::Dumper. It may not work on 100% of all code, but it's close (leaving aside issues of closures, which you would also have with bytecode), and when bugs are reported they do get fixed promptly.

      Thanks for the interesting pointer, I guess this won't be solved gracefully until the advent of Perl6. I should have mentioned that I'm using Perl 5.6.1 on Debian stable, for which I'm sure B::Bytecode is not intended :)

      Running the subroutine source through Data::Dumper is the plan for production, just my mind wouldn't let go of the idea since its quite easy in Python.
        B::Bytecode is a core module, and is included in 5.6.1.
        Er, but why do you *want* the bytecode?