Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Saving sub routines.. Is it possible?

by grinder (Bishop)
on Apr 05, 2008 at 15:45 UTC ( [id://678539]=note: print w/replies, xml ) Need Help??


in reply to Saving sub routines.. Is it possible?

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

Replies are listed 'Best First'.
Re^2: Saving sub routines.. Is it possible?
by cosmicperl (Chaplain) on Apr 05, 2008 at 16:00 UTC
    Data::Dump::Streamer looks great... But I'm trying to keep to core modules.
    I'm coming up with another solution I think will work for my scenario. I'll post it shortly.
    My program has lots of user account and lots of different config options for each one. Calculations are made based on the options. When sorting through making overall calculations for a long list of users I need to be able to change variable values quickly. Some accounts will use default values, others part of a group of values and others individual. Main user data is obviously stored in a database, but these variables are stored in small flat files for quick access.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://678539]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-04-18 13:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found