#
# This software is Copyright 2005 by Elsevier Inc.  You may use it
# under the terms of the license at http://perl.plover.com/hop/LICENSE.txt .
#



###
### rpn_ifelse
###

## Chapter 2 section 2

my $result = evaluate($ARGV[0]);
print "Result: $result\n";

sub evaluate {
  my @stack;
  my ($expr) = @_;
  my @tokens = split /\s+/, $expr;
  for my $token (@tokens) {
    if ($token =~ /^\d+$/) {   # It's a number
      push @stack, $token;
    } elsif ($token eq '+') {
       push @stack, pop(@stack) + pop(@stack);
    } elsif ($token eq '-') {
       my $s = pop(@stack);
       push @stack, pop(@stack) - $s
    } elsif ($token eq '*') {
       push @stack, pop(@stack) * pop(@stack);
    } elsif ($token eq '/') {
       my $s = pop(@stack);
       push @stack, pop(@stack) / $s
    } else {
      die "Unrecognized token `$token'; aborting";
    }
   }
  return pop(@stack);
}
