First, only consider as valid tokens sequences of non-space characters. Second, if a token doesn't look like a number, make sure a handler exists in the %operators
hash. I find push and pop more natural when dealing with a stack, but that doesn't really matter;
#!/usr/bin/env perl
use strict;
use warnings;
# Turn on autoflush
local $| = 1;
use Scalar::Util qw(looks_like_number);
my %operators = (
'+' => \&add,
'-' => \&subtract,
'*' => \&multiply,
'/' => \÷,
);
print 'Enter an expression to evaluate : ';
my $input = <STDIN>;
my @tokens = split ' ', $input;
my @stack;
for my $token (@tokens) {
if (looks_like_number($token)) {
push @stack, $token;
}
else {
if (exists $operators{$token}) {
my $op = $operators{$token};
my $x = pop @stack;
my $y = pop @stack;
push @stack, $op->($x, $y);
}
else {
warn "Unknown token '$token'\n";
}
}
}
print "Answer: $stack[-1]\n";
sub add { $_[0] + $_[1];}
sub multiply { $_[0] * $_[1];}
sub subtract { $_[0] - $_[1];}
sub divide { $_[0] / $_[1];}