in reply to Simple add and multiply subroutines

As written, given arguments add 1 7 9, you are passing 1..9 to add(), which would result in 45. To pass 1,7,9, you would use a slice of the array, like so: add(@ARGV[1..$i]).

But it would be nicer to separate your arguments up front:

my ($operation, @operands) = @ARGV or die usage(); if ($operation eq 'add') { my $sum = add(@operands); ...

Replies are listed 'Best First'.
Re^2: Simple add and multiply subroutines
by negzero7 (Sexton) on Apr 08, 2008 at 02:41 UTC

    Woot I think I got it. Check it out (I also added comments)

    use warnings; use strict; my $i = $#ARGV; #Scalar for array length if ($ARGV[0] eq "add") { #Checks for add my $rtn = add(@ARGV[1..$i]); #Calls add subroutine print "The sum is: $rtn"; } elsif ($ARGV[0] eq "multiply"){ #Checks for multipl +y my $rtn = multiply(@ARGV[1..$i]); #Calls multiply subroutine print "Their product is: $rtn"; } sub add { #add subroutine my ($sum); $sum=0; foreach $_(@_) { #Loops through the array $sum +=$_; #Adds each array element to the r +est } return $sum; #Returns the sum value } sub multiply { #multiply subroutine my $product=1; foreach $_(@_) { #Loops through the array $product*=$_; #Multiplys each element to last } return $product; #Returns the product value }

    How does that look?