Math::Symbolic::Compiler is a Perl module that can compile Math::Symbolic trees to Perl code.
# A tree to compile
my $tree = Math::Symbolic->parse_from_string('a^2 + b * c * 2');
# The Math::Symbolic::Variable 'a' will be evaluated to $_, etc.
my $vars = [qw(b a c)];
my ($closure, $code, $trees) =
print $closure->(2, 3, 5); # (b, a, c)
# prints 29 (= 3^2 + 2 * 5 * 2)
($closure, $trees) =
($code, $trees) = Math::Symbolic::Compiler->compile_to_code($tree, $vars);
This module allows to compile Math::Symbolic trees to Perl code and/or anonymous subroutines whose arguments will be positionally mapped to the variables of the compiled Math::Symbolic tree.
The reason you'd want to do this is that evaluating a Math::Symbolic tree to its numeric value is extremely slow. So is compiling, but once you've done all necessary symbolic calculations, you can take advantage of the speed gain of invoking a closure instead of evaluating a tree.