Return subroutine reference.
Here is a simple example that creates sub refs closed above a value:
my $add_5_to = add_x_to(5); print $add_5_to->(7), "\n"; sub add_x_to { my $x = shift; return sub { my $value = shift; return $x + $value; }; }
You can also work with subs names like:
sub op { my $name = shift; return $op eq 'add' ? \&add : sub {}; } sub add { my $l = shift; my $r = shift; return $l + $r; }
You can use eval with an arbitrary string, but do not do this. The code is hard to read, and it restarts compilation, which slows everything down. There are few cases where the eval string is the best tool to work with. Whenever an eval string seems like a good idea, you will almost certainly be better off with a different approach.
Almost everything you would like to do with the eval string can be achieved with closures.
source share