Created
September 25, 2019 02:40
-
-
Save Mister-Ed/00db967aa0f48657026dce0649450357 to your computer and use it in GitHub Desktop.
Simple RPN Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -T | |
# Web script version: | |
# Takes RPN strings and computes final value. | |
# Places numbers on stack, pops last 2 off to compute operation and | |
# then adds answer onto stack until only one number left in the stack array. | |
my $operator = '[-+*/^]'; | |
my @tests = ('3 4 + 1 1 + + 3 /','3 4 2 * 1 5 - 2 3 ^ ^ / +'); | |
my @stack; | |
my $answer; | |
print "Content-type: text/html\n\n"; | |
print "<h1>RPN Calculator</h1><br>"; | |
foreach $itm (@tests) { | |
chomp $itm; | |
$itm =~ s/\s+/ /g; | |
print "Solving RPN: <i>$itm</i><br><br>"; | |
@line = split(/ /, $itm); | |
foreach $line_item (@line) { | |
#print "\$line_item = $line_item <br>"; | |
if ( $line_item =~ /\d+/ ) { | |
push(@stack, $line_item); | |
#print "added $line_item to stack <br><br>"; | |
} | |
elsif ( $line_item =~ /($operator)/ ) { | |
$y = pop(@stack); | |
$x = pop(@stack); | |
if ($1 eq '*') { | |
$answer = $x * $y; | |
} | |
elsif ($1 eq '-') { | |
$answer = $x - $y; | |
} | |
elsif ($1 eq '+') { | |
$answer = $x + $y; | |
} | |
elsif ($1 eq '/') { | |
$answer = $x / $y; | |
} | |
elsif ($1 eq '^') { | |
$answer = $x ** $y; | |
} | |
push(@stack, $answer); | |
#print "added $answer to stack <br>"; | |
print "operation: $x $1 $y = $answer <br>"; | |
} | |
} | |
$x = pop(@stack); | |
print "<br><b>Final Answer = " . $x . '</b><br><br><br>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment