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?

2
  • 8
    Perl's system function doesn't handle array reference arguments very well (unless you have a program called ARRAY(0xa63af0) in your path). Commented Mar 11, 2011 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. Commented Mar 12, 2011 at 20:34

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.