Friday, May 21, 2010

How do you pass an array of numbers to a subroutine as a referecence in Perl.?

And in particular how would you do in it with this program for the add and multiply subroutine ?





my ($rtn, $len);





$len = @ARGV;





# If first argument is add, run add function; if multiply, run multiply


# function, otherwise warn user and end script


if ($ARGV[0] =~ /add/) {


$rtn = %26amp;add(@ARGV);


print "The sum is: $rtn\n";


}





elsif ($ARGV[0] =~ /multiply/) {


$rtn = %26amp;multiply(@ARGV);


print "The product is: $rtn\n";


}





else {


print "\nInvalid request, please use \"add\" or \"multiply\"\n";


print "followed by some numbers.\n";


}





# Subroutine definitions #


sub add


{


my ($sum, $i);


$sum = 0;


for ($i = 1; $i %26lt;= $len; $i++)


{


$sum += $_[$i];


}


$sum;


}


sub multiply


{


my ($product, $i);


$product = 1;


for ($i = 1; $i %26lt; $len; $i++)


{


$product *= $_[$i];


}


$product;


}

How do you pass an array of numbers to a subroutine as a referecence in Perl.?
the code works as posted!


%perl x.pl add 1 2 4


The sum is: 7


% perl x.pl multiply 1 2 4


The product is: 8








but this uses better perl trickery!


# If first argument is add, run add function; if multiply, run multiply


# function, otherwise warn user and end script


$cmd = shift @ARGV;


if ($cmd =~ /add|multiply/) {


$rtn = %26amp;$cmd(@ARGV);


print "The result is: $rtn\n";


}


else {


print "\nInvalid request, please use \"add\" or \"multiply\"\n";


print "followed by some numbers.\n";


}





# Subroutine definitions #


sub add


{


my $sum = 0;


$sum += $_ foreach @_;


return $sum;


}


sub multiply


{


my $prod = 1;


$prod *= $_ foreach @_;


return $prod;


}


No comments:

Post a Comment