In Monads in Perl, sleepingsquirrel gives an example of how to parse a prefix-notation equation using monads. After reading the article, I really couldn't see the point of monads (they seem just like functions with an implicit state). However, the prefix equations used in the article seemed like a perfect place to apply the sexeger technique.

As an added bonus, this version features per-operator callbacks.

use strict; use warnings 'all'; # to call: my %handlers = ( 'Div' => sub { $_[0] / $_[1] }, 'Mul' => sub { $_[0] * $_[1] }, 'Mod' => sub { $_[0] % $_[1] }, 'Exp' => sub { $_[0] ** $_[1] } ); print eval_prefix_equation("Mul Mod Exp Div Mul Div Div Con 18 Con 2 C +on 3 Con 4 Con 6 Con 2 Con 3 Con 4", \%handlers); # the method: sub eval_prefix_equation { my ($s,$h) = @_; my $r = reverse $s; # qr/Con (\d+(?:\.\d+)?/ backwards my $con = qr/(\d+(?:\.\d+)?) noC/; my $op = '(' . join('|', map { scalar reverse $_ } keys %$h) .')'; # just a sexeger; the while-loop condition resets our pos for us. $r =~ s/ $con \s+ $con \s+ $op / reverse('Con ' . $h->{reverse $3}( scalar(reverse $2), scalar(reverse $1) )); /ex while $r =~ /$op/; return scalar reverse $r; }

In reply to Parsing/Evaluating a prefix-notation equation using sexeger by jryan

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.