How exactly can I pass both scalar variables and array variables to a subroutine in Perl?
my $currVal = 1;
my $currValTwo = 1;
my @currArray = ('one','two','three');
my @currArrayTwo =('one','two','three');
&mysub($currVal, $currValTwo,\@currArray, \@currArrayTwo);
sub mysub() {
# That doesn't work for the array as I only get the first element of the array
my($inVal, $inValTwo, @inArray, @inArrayTwo) = @_;
}
You pass the arguments as references, so you need to dereference them to use the values. Be careful about whether you want to change the original array or not.
This will change the original
@currArrayTwo
, which might not be what you want.This will only copy the values and leave the original array intact.
Also, you do not need the ampersand in front of the sub name, from perldoc perlsub:
You do not need empty parens after your sub declaration. Those are used to set up prototypes, which is something you do not need to do, unless you really want to.
So, for example: This is a using statement to search something in an array:
This is the sub declaration:
This is the call to the sub (last parameter is: Default index value to give back if not found)
This is the routine:
You need to fetch them as references because you've already passed them as references (by using the
\
operator):and then use the references as arrays: