home *** CD-ROM | disk | FTP | other *** search
- #!/usr/bin/perl
-
- &driver;
-
- # First, the driver loop.
-
- sub driver {
- while (<>) { # For each line.
- s/\s+//g; # Remove all white space, \n included.
- $val = &expr; # Evaluate the expression.
- die "Expected an operator: $_\n" unless $_ eq "";
- print "$val\n";
- }
- exit;
- }
-
- # Parse an expression.
-
- sub expr {
- local($left, $op, $right);
-
- $left = &term;
- while ($op = &addop) {
- $right = &term;
- if ($op eq '+')
- { $left += $right; }
- else
- { $left -= $right; }
- }
- $left;
- }
-
- sub addop {
- s/^([+-])// && $1;
- }
-
- # Parse a term.
-
- sub term {
- local($left, $op, $right);
-
- $left = &factor;
- while ($op = &mulop) {
- $right = &factor;
- if ($op eq '*')
- { $left *= $right; }
- else
- { $left /= $right; }
- }
- $left;
- }
-
- sub mulop {
- s#^([*/])## && $1;
- }
-
- # Parse a factor.
-
- sub factor {
- local($val);
- if (s/^([\d.]+)//) { # Found a number.
- $val = $1;
- }
- elsif (s/^\(//) { # Found a parenthesized expr.
- $val = &expr;
- s/^\)// || die "Missing right paren: $_\n";
- }
- else {
- die "Expected a factor: $_";
- }
- $val;
- }
-