in reply to Simple add and multiply subroutines
You have a major error in that you are using the range operator which will not work correctly, for example:
$ perl -le'my @x = $ARGV[1] .. $ARGV[$#ARGV]; print "@x"' add 12 8 +2 $ perl -le'my @x = $ARGV[1] .. $ARGV[$#ARGV]; print "@x"' add 2 8 1 +2 2 3 4 5 6 7 8 9 10 11 12
You should probably shift the first argument off @ARGV, something like this:
use warnings; use strict; my $i = shift; if ( $i eq 'add' ) { my $rtn = add( @ARGV ); print "The sum is: $rtn"; } elsif ( $i eq 'multiply' ){ my $rtn = multiply( @ARGV ); print "Their product is: $rtn"; } sub add { my $sum = 0; foreach ( @_ ) { $sum += $_; } return $sum; } sub multiply { my $product = 1; foreach ( @_ ) { $product *= $_; } return $product; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Simple add and multiply subroutines
by negzero7 (Sexton) on Apr 08, 2008 at 02:31 UTC | |
|
Re^2: Simple add and multiply subroutines
by Anonymous Monk on Nov 16, 2009 at 01:19 UTC |