#!/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