I'm looking to make a subroutine mysub
which should behave such that the following two calls are effectively the same.
mysub(["values", "in", "a", "list"]);
mysub("Passing", "scalar", "values");
What is the proper syntax to make this happen?
To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. Now to use that procedure: int B[100]; zero(B, 100);
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
You can't pass arrays to functions. Functions can only accept a lists of scalars for argument. As such, you need to pass scalars that provide sufficient data to recreate the arrays.
Check if @_
contains a single array reference.
sub mysub {
if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
# Single array ref
} else {
# A list
}
}
The if
clause checks that only one argument was passed and that the argument is an array reference using ref
. To make sure that the cases are the same:
sub mysub {
if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
@_ = @{ $_[0] };
}
# Rest of the code
}
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