Possible Duplicate: How do pass one array and one string as arguments to a function?
I have a function, or subroutine, that takes in the first parameter as an array and the second parameter as a scalar. For example,
sub calc { my @array = $_[0]; my $scalar = $_[1]; print @array, $scalar; }
The problem is that the function is making the array equal to the first value of the array passed in, and the scalar to be the second value of the array passed in. When I want the first array to be the entire array, I do not need to make a deep copy of the array. For example,
my @array = ('51', 'M'); my $scalar = 21;
and
calc(@array, $scalar)
will print 51 M
when I want 51 M 21
.
You have to pass them like this: two_array_sub( @$arr_ref, @$brr_ref ); However, because making "array expressions" gets really ugly quickly with arrays nested deep, I often avoid Perl's fussiness as you can overload the type of reference Perl will take by putting it in a "character class" construct.
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.
Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.
You need to pass it in as a reference:
calc(\@array, $scalar)
And then access it as: my @array = @{$_[0]};
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