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) = @_;
}
A scalar variable can store either a number, a string, or a reference and will precede by a dollar sign ($). An array variable will store ordered lists of scalars and precede by @ sign. The Hash variable will be used to store sets of key/value pairs and will precede by sign %.
Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.
Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a parameter and an array variable @_ is used to accept the list value inside of the subroutine or function.
You need to fetch them as references because you've already passed them as references (by using the \
operator):
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
and then use the references as arrays:
@{$inArray}
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.
sub mysub {
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
@{$inArrayTwo} = ('five','six','seven');
}
This will change the original @currArrayTwo
, which might not be what you want.
sub mysub {
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;
my @ATwo = @{$inArrayTwo};
@ATwo = ('five','six','seven');
}
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:
If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With