Your bug is that $SubRef is interpolated into the eval.
Oops. But you don't need to do that:
sub Half
{
my $n = shift;
my $SubBody = Power_Of_Two( $n ) ?
"return \$_[$[] >> Log2( $n );" :
"return int( \$_[$[] / $n );";
my $code = "sub { $SubBody }";
my $sub = eval $code;
die "Code '$code' gave error $@" if $@;
return $sub;
}
But given the overhead of entering an anonymous function it
is not worth looking for optimizations this way. Instead
stop and think about "optional hooks" in your code. Where
closures rock is as a way to provide optional hooks when you
compile a function without paying any run-time price if the
hook was not included. So instead of doing run-time checks
for whether debugging (for instance) is on, make the
debugging checks be inserted or not when you create the
string to eval for the sub.
As the rule goes, optimize on the level of big design
decisions, not faster local constructs.