Saturday, July 24, 2010

Perl: mucking with the symbol table

Suppose you want to be able to build a function on the fly (as a closure) then call it like any other subroutine. Your answer is to modify the symbol table, to wit:
$sub1 = sub {
print "Hi!\n";
};

$clo2 = sub {
print "OK?\n";
local *sub1 = $sub1;
sub1();
};

$clo2->();


sub1();
Here, the call to $clo2 will print "OK?", then "Hi!", then the second attempt to call sub1() will fail because it's not defined (we localized the typeglob within $clo2).

This is how I've implemented subroutines in Semantics::Code.

No comments:

Post a Comment