5

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?

ajwood
  • 18,227
  • 15
  • 61
  • 104
  • 8
    Perl's `system` function doesn't handle array reference arguments very well (unless you have a program called `ARRAY(0xa63af0)` in your path). – mob Mar 11 '11 at 21:31
  • Hmmm... This is still what I want. I'm not sure what made be think this is how system works. Thanks, I'll edit my question. – ajwood Mar 12 '11 at 20:34

1 Answers1

18

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
}
toolic
  • 57,801
  • 17
  • 75
  • 117
Tim
  • 13,904
  • 10
  • 69
  • 101