#!/usr/bin/perl -w use strict; # # Declaring subroutine prototypes here allows us to define the # subroutines at the end of the file. # sub parse_line( $ ); sub calculate( $$$ ); while(<>) { chomp; # # Stop if the user typed 'exit'. # last if /^exit$/; # # Call subroutines parse_line() and calculate() to do the actual work # my($op, $n1, $n2) = parse_line($_); my $result = calculate($op, $n1, $n2); # # Print the results. # print "$n1 $op $n2 = $result\n"; } # # Extract numbers and operator from input string # sub parse_line( $ ) { local($_) = @_; # so we don't have to use =~ # # use m%% so we can use / inside the expression # if (m%^\s*(\d+)\s*([-+*/])\s*(\d+)\s*$%) { return ($2, $1, $3); # operator, then the two numbers } else { die "Unable to parse: \"$_\"\n"; } } # # Compute the value # sub calculate( $$$ ) { my($op, $n1, $n2) = @_; if ($op eq '+') { return $n1 + $n2; } elsif ($op eq '-') { return $n1 - $n2; } elsif ($op eq '*') { return $n1 * $n2; } elsif ($op eq '/') { return $n1 / $n2; } else { die "Unrecognized operator: \"$op\"\n"; } }