You're just begging for trouble with this, unless you set yourself up a good bit more structure. The problem is that perl "coderef"s are not just references to compiled code. They are
closures. In other words, they contain an imutable reference to the context in which they were instantiated. Take the code from one closure, and use it to instantiate another closure in another context, and they will be different things (and potentially behave differently).
Here's a quick and dirty example (try it!)
my $x = 0;
my $sub1 = sub { print "$x\n" };
my $sub2;
{
my $x = 10;
$sub2 = sub { print "$x\n" };
}
&$sub1;
&$sub2;
The output will be:
0
10
even though $sub1 and $sub2 originate from exactly the same code!
Speaking from experience with similar sorts of situations, what I would recomend is: don't store a coderef... just store the code as a character string, and eval it in context. This gives you dynamic lexical scoping, as opposed to static lexical scoping (closures), which is (possibly) more what you want to happen. Same example, converted:
my $x = 0;
my $sub1 = q{ print "$x\n" };
my $sub2;
{
my $x = 10;
$sub2 = q{ print "$x\n" };
}
eval $sub1; die $@ if $@ ne "";
eval $sub2; die $@ if $@ ne "";
This will give you:
0
0
That is: the same output from the same code, regardless of the context in which you instantiated the code.
-------
:Wq
Not an editor command: Wq
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.