Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a subroutine that accepts an array *or* a variable number of scalars?

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?

like image 216
ajwood Avatar asked Mar 11 '11 20:03

ajwood


People also ask

How do you use an array as a parameter?

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);

When we pass array to a function that is passed as?

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.

How do I pass multiple arrays to a subroutine in Perl?

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.


1 Answers

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
}
like image 100
Tim Avatar answered Sep 28 '22 15:09

Tim