I am writing a little application in C, and after getting totally sick of basically reinventing a scripting language for that program, I decided to embed a little perl. For this, I need to tinker with the syntax:

Case: I want a function called 'on' that will take two code blocks, 'when' ($_ = line to be matched, returns true if matches) and 'then' (if 'when' was true, run 'then' with $_ = modifiable typeglob to the line to be matched).

Clarification:
then={ /foo/ }
when={ tr/ab/ba/; }
$line="abba is kind of foo";

After calling on with proper parameters,
$line eq "baab is kind of foo"

After tinkering for a while (and reading the try/catch example), I came up with this:

sub on (&$$) { my($f1,$f2,$l)=@_; local $_=$$l; if (&$f1) { local *_=$l; &$f2($l); } } sub action (&) { shift } $a="abba is foo"; on { /foo/ } action { tr/ab/ba/; },\$a; print "$a\n";

And lo! It works. Now, what's the point, and why is this in Seekers, you ask. Well...

At this point it becomes evident how similar this is to perl grep. However, grep has one magical power I don't: It can take EXPR or BLOCK as its 1st parameter. How do I?

Intuitive solution one, write two functions called 'on' with different prototypes. Meep! Prototype mismatch.

Intuitive solution two, ditch prototypes and figure out what we are doing by looking at the parameter list. Meep! Syntax error follows.

How do I manage?

Issue two, rather minor though, is that I'd like to rid myself of the 'action' keyword and just write the two code blocks like this: on { /foo/ } { tr/ab/ba/; },\$a;

But I couldn't figure out any way to do without that dummy sub action, everything resulted in obscure syntax errors.

-Kaatunut


In reply to Polymorphic prototypes? (creating new syntax) by kaatunut

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.