#!/usr/bin/perl -w use strict; while(<>) { chomp; print recursum($_), "\n"; } sub recursum { # # Copy first parameter to $_ but make a local copy, so that # changes made here can't hurt contents of $_ outside this # subroutine call. # local($_) = @_; # # Base case - if string contains just a number, we're done. # if (/^\s*(\d+)\s*$/) { return $1; } # # Take two numbers and the operator off the front, and put # everything after that into $rest. # elsif (/^\s*(\d+)\s*([+-])\s*(\d+)\s*(.*)/) { my($n1, $op, $n2, $rest) = ($1, $2, $3, $4); my $sum; # # Because of the regular expression, $op is either + or -, so # no need for elsif here. # if ($op eq '+') { $sum = $n1 + $n2; } else { $sum = $n1 - $n2; } # # Combine our calculation with $rest and recurse... # return recursum("$sum $rest"); } else { die "Unable to parse \"$_\"\n"; } }