Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I'm working on a project that wants me to use references to pass array elements into a subroutine where it will either add them, or multiply them (user specified). I got it to work perfect without using references but now that I have to use them, it isn't even making it through the interpreter (comiler?).
Take a look and see if you can help me out with some tips and pointers.
use warnings; use strict; my $ref = \@ARGV; if ($ARGV[0] eq "add") { #Checks for add my $rtn = add(@{$ref}); #Calls add subroutine print "The sum is: $rtn"; } elsif ($ARGV[0] eq "multiply") { #Checks for multiply my $rtn = multiply(@{$ref}]); #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 }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: references to subroutines
by dragonchild (Archbishop) on Apr 12, 2008 at 21:37 UTC | |
|
Re: references to subroutines
by moritz (Cardinal) on Apr 12, 2008 at 21:47 UTC | |
|
Re: references to subroutines
by apl (Monsignor) on Apr 13, 2008 at 01:06 UTC | |
|
Re: references to subroutines
by jethro (Monsignor) on Apr 13, 2008 at 11:11 UTC |