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,
Erik

In reply to Closures! I pity da fool! by erikharrison

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.