Can this be done?

This is Perl, of course it can be done. In this particular case, we need to avail ourselves of demerphq's most excellent Data::Dump::Streamer.

Even then, a major imposition is that you have to use package variables, since lexical variables can't be injected into scope from an eval.

You can take your data structure and dump it out, being careful to name it so that you can find it again:

use strict; use warnings; use Data::Dump::Streamer; use vars qw($hash $var1 $var2); $hash->{subs}->[0] = sub { $var1 = "a"; $var2 = "b"; }; $hash->{subs}->[1] = sub { $var1 = "c"; $var2 = "d"; }; Dump($hash)->Names('$hash')->Out;

This writes the sub to STDOUT. You will probably want to write it to a filehandle; read the documentation to find out how to do that.

You can then thaw the subroutines by eval'ing the resulting dumped code:

use strict; use warnings; use vars qw($hash $var1 $var2); my $file = shift or die "No file given\n"; open my $in, '<', $file or die "input $file: $!\n"; eval do { local $/ = undef; <$in>; }; $var1 = 'foo'; print "var1 = $var1\n"; $hash->{subs}[1]->(); print "var1 = $var1\n";

You will observe that $var1 changes its value after calling the subroutine. Be that as it may, this is a pretty odd thing to want to do. If it's not impolite, I'm curious to know what you want to use it for.

• another intruder with the mooring in the heart of the Perl


In reply to Re: Saving sub routines.. Is it possible? by grinder
in thread Saving sub routines.. Is it possible? by cosmicperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.