Does the following PERL program pass a list/array of numbers to the add and multiply subroutine as a referecence or does it not? And if doesn't how can make it do this.
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;
}
Does the following PERL program pass a list/array of numbers to the add an multiply subroutine as a referecenc
It does not. Calling subroutine(@list) passes the list by value, not by reference. To pass a reference, put \ before the array name:
multiply(\@ARGV);
You'll also need to change the subruotines to work with their arguments being an array reference, to something like:
sub add {
my $sum=0;
$sum += $_ for @{$_[0]};
return $sum;
}
(by the way, "Perl" is the language, "perl" is the interpreter, "PERL" does not exist)
birthday cards
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment