OK ... now for a quick round of golf. Here's a version that's a bit tighter and easier to expand:
#!/usr/bin/perl -w use strict; use warnings; my @stack = (); sub binop { my ($op, $prec) = @_; my ($rhop, $rhprec) = @{pop @stack}; my ($lhop, $lhprec) = @{pop @stack}; # Wrap operand(s) with lower precedence $lhop = '(' . $lhop . ')' if $prec > $lhprec; $rhop = '(' . $rhop . ')' if $prec > $rhprec; push @stack, [ $lhop . $op . $rhop, $prec ]; } my %handlers = ( 'push' => sub { push @stack, [shift, 999]; }, 'print' => sub { print "out: '" . ${@{pop @stack}}[0] . "'\n"; + }, 'add' => sub { binop '+', 1; }, 'mul' => sub { binop '*', 2; } ); while (<DATA>) { chomp; print "TOS='" . (@stack ? $stack[$#stack][0] : '-nil-') . "' " . "stmt = '" . $_ . "'\n"; my ($operator, $operand) = split; if ($handlers{$operator}) { $handlers{$operator}->($operand); } else { print "Unknown operator: '$operator' for line '$_'\n"; } } __DATA__ push 3 push 5 add push apples add push oranges push 9 push bananas push peels mul add add mul print
Which gives us:
TOS='-nil-' stmt = 'push 3' TOS='3' stmt = 'push 5' TOS='5' stmt = 'add' TOS='3+5' stmt = 'push apples' TOS='apples' stmt = 'add' TOS='3+5+apples' stmt = 'push oranges' TOS='oranges' stmt = 'push 9' TOS='9' stmt = 'push bananas' TOS='bananas' stmt = 'push peels' TOS='peels' stmt = 'mul' TOS='bananas*peels' stmt = 'add' TOS='9+bananas*peels' stmt = 'add' TOS='oranges+9+bananas*peels' stmt = 'mul' TOS='(3+5+apples)*(oranges+9+bananas*peels)' stmt = 'print' out: '(3+5+apples)*(oranges+9+bananas*peels)'
--roboticus

In reply to Re^2: Convert stack-based code to "conventional" (was Re: Graphing SQLite's VDBE) by roboticus
in thread Graphing SQLite's VDBE by bsb

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.