Alright, trying to wrap my head around something a little challenging for once . . .
All of this is part of a super secret project to implement a small language in Perl - and I have no idea what I am doing. I can't figure out how to make binary operators work, so I'm writing subroutines to implement them, and (hopefully) the parser will turn binops into appropriate calls to these subs.
In order to save my fingers, I decided to generate the subs with a closure, like so:
sub make_bin_ops { my $op = shift; return sub { my ($a, $b) = @_; return eval "$a $op $b"; } } my ($div_OP) = make_bin_ops('/');
This seems to work (but since I'm not always sure about closures, I wouldn't be surprised to learn otherwise).
I decided, however, that the eval in the return sub ref was probably a performance hit. So I decided to use eval instead to return a sub ref that used the operator directly, like so:
sub make_bin_ops { $op = shift; $func = "sub { my (\$a, \$b) = \@_ return \$a $op \$b; }"; return eval $func; } my ($div_OP, $mult_OP) = make_bin_ops('/'), make_bin_ops('*'); print &$div_OP(2,2); print &$mult_OP(2,2);
This however, does not seem to work. Perl tells me I'm calling an undefined subroutine - what gives?
ps - if someone can redirect me to a mortal comprhendable discussion of language implementation on the web, I'd be much appreciative.
Cheers,In reply to Closures! I pity da fool! by erikharrison
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |