How to make a routine that takes an array of * or * a variable number of scalars?

I want to make a subroutine mysubthat should behave so that the next two calls are virtually the same.

mysub(["values", "in", "a", "list"]);
mysub("Passing", "scalar", "values");

What is the correct syntax for this to happen?

+5
source share
1 answer

Make sure it @_contains a reference to a single array.

sub mysub {
    if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
        # Single array ref
    } else {
        # A list
    }
}

The sentence ifchecks that only one argument is passed, and that the argument is an array reference using ref. To make sure the cases are the same:

sub mysub {
    if ( @_ == 1 && ref( $_[0] ) eq 'ARRAY' ) {
        @_ = @{ $_[0] };
    }
    # Rest of the code
}
+18
source

All Articles