first commit
This commit is contained in:
34
perl/Examples/Chap2/rpn-ifelse
Normal file
34
perl/Examples/Chap2/rpn-ifelse
Normal file
@@ -0,0 +1,34 @@
|
||||
|
||||
|
||||
###
|
||||
### 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);
|
||||
}
|
||||
Reference in New Issue
Block a user