Reverse Polish Calculator
A simple Perl command-line reverse polish calculator.
#!/usr/bin/perl #Usage: #~$ perl rpn.pl "(3 (3 20 *) +)" #(3 (3 20 *) +) = #63 $str = $ARGV[0]; $str =~ s/[\(\)]//g; @expr = split(" ", $str); @stack = (); print $ARGV[0] . " = \n"; while($item = shift(@expr)) { if($item eq "+") { push(@stack, pop(@stack)+pop(@stack)); } elsif($item eq "-") { push(@stack, -pop(@stack)+pop(@stack)); } elsif($item eq "*") { push(@stack, pop(@stack)*pop(@stack)); } elsif($item eq "/") { push(@stack, 1/pop(@stack)*pop(@stack)); } else { push(@stack, sprintf("%.3f",$item)); } } print @stack; print "\n";

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here