in reply to Saving code from an anonymous coderef

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