By looking at that most perl programmers would know that it takes 3 mandatory vars, and an optional 4th;
You could also use a runtime check. Compare the subroutines foo and bar:
my @x = @_;
die "Incorrect number of arguments$!" if @x < 3 || @x > 4;
print "$_\n" for @x;
sub bar ($$$;$)
my @y = @_;
print "$_\n" for @y;
Both approaches are self-documenting. The advantage of using prototypes is that violations are detected at compile time, which is more efficient. The disadvantage is that the calling syntax is much more restrictive. For example:
my @args = (2, 3, 5, 7);
works as expected, but
results in a compilation error because the first $ prototype puts @args into scalar context, resulting in a single value of 4 (the number of elements in the array). To call bar successfully in this situation you would need something ugly like this:
bar($args, $args, $args, $args);
Of course, prototypes can be useful; but when you write:
I always use prototypes -- even on methods where they don't matter -- for no other reason than, minimally, documentation. It's a self-imposed discipline.
this sounds (to me) like an attempt to convert Perl into a statically typed language. Much better to embrace Perl’s dynamic nature, use natural Perl idioms by default, and save prototypes for those (rare) situations in which they’re really useful.
See Far More than Everything You've Ever Wanted to Know about Prototypes in Perl -- by Tom Christiansen.
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:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||