in reply to Saving code from an anonymous coderef
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.
|
|---|