This problem is not solvable without placing restrictions on what can be in the array or how the array reference looks.
In your solution above, you distinguish based on number of arguments passed, which prevents you from passing an array of one element (which may or may not be just fine for your purpose).
You could instead choose to check the ref type of the parameter: if (ref $_[0] eq "ARRAY") { ... } else { ... } which would prevent you from passing an array whose first element was an array reference. (Variations on this involve UNIVERSAL::isa($_[0], "ARRAY") or calling an isa method on an object or doing an array dereference in an eval block to see if it fails; this subproblem of "what is an array reference" also has no perfect solution.)
Or combine both the check for one element and the check for an array ref.
There are also prototypes; if you promise to not use them as if they were what other languages call prototypes,
you can give your sub a (\@) prototype; then just call it
as foo(@array) and $_[0] will automatically be a ref to the array; if you want to pass an array ref instead, say sub(@$arrayref), which will place the reference in $_[0] (without the actual overhead of expanding the array into a list).
All in all, it's best to document what your routine expects and take only that input; do you really need to accept both?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.