[1] push 3
[2] push 5
[3] add
[4] push 7
[5] push 9
[6] add
[7] mul
[8] print
####
#!/usr/bin/perl -w
use strict;
use warnings;
my @stack = ();
while () {
chomp;
print "TOS='" . (@stack ? $stack[$#stack] : '-nil-') . "', "
. "stmt = '" . $_ . "'\n";
my ($operator, $operand) = split;
if ($operator eq 'push') {
push @stack, $operand;
}
elsif ($operator eq 'print') {
print "out: '" . (pop @stack) . "'\n";
}
elsif ($operator eq 'add') {
my $lhs = pop @stack;
my $rhs = pop @stack;
push @stack, '(' . $lhs . ' + ' . $rhs . ')';
}
elsif ($operator eq 'mul') {
my $lhs = pop @stack;
my $rhs = pop @stack;
push @stack, '(' . $lhs . '*' . $rhs . ') ';
}
}
__DATA__
push 3
push 5
add
push 7
push 9
add
mul
print
####
root@swill ~/PerlMonks
$ ./stack_to_infix.pl
TOS='-nil-', stmt = 'push 3'
TOS='3', stmt = 'push 5'
TOS='5', stmt = 'add'
TOS='(5 + 3)', stmt = 'push 7'
TOS='7', stmt = 'push 9'
TOS='9', stmt = 'add'
TOS='(9 + 7)', stmt = 'mul'
TOS='((9 + 7)*(5 + 3)) ', stmt = 'print'
out: '((9 + 7)*(5 + 3)) '
root@swill ~/PerlMonks
$