paurus has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

Being new with Perl I am stumbling about in confusion. I am attempting to write a simple calculator which takes the elements from a user entered array (consisting of more than 2 elements), then adds, subtracts, etc.. the elements.

The problem I am having is how to keep a running result of the subtraction value. I only know how to subtract single elements such as:
$c = $a - $b;
What I am looking to do is get a final subtracted value. This is where I have stalled:
... code ... sub subtraction{ chomp(@_ = split(" ", <STDIN>)); # user enters values on one line foreach(@_) { $result -= $_; # I guess I am using the WRONG operator } print "Result: $result\n\n"; ... rest of subroutine code ... }
So if the array was 4 3 1, the result would be (4 - 3 - 1) = 0

Your help has always been timely and invaluable in the past. Any hints as to the proper way to implement this code are very appreciated since I plan to extrapolate (if possible) your aid into the multiplication and division components of this script. Thank you.

Replies are listed 'Best First'.
Re: simple math
by ysth (Canon) on Apr 22, 2004 at 04:16 UTC
    You are doing everything right except assigning the first value to $result; try $result = shift(@_) just before the foreach.
Re: simple math
by Abigail-II (Bishop) on Apr 22, 2004 at 09:27 UTC
    A quick and dirty trick:
    sub subtraction { local $" = "-"; eval "@{[split ' ' => scalar <STDIN>]}"; }

    It won't be the fastest solution though.

    Abigail