in reply to Re^6: How to return values from a hash?
in thread How to return values from a hash?
Hello perl-diddler,
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:
#! perl use strict; use warnings; sub foo { my @x = @_; die "Incorrect number of arguments$!" if @x < 3 || @x > 4; print "$_\n" for @x; print "\n"; } sub bar ($$$;$) { my @y = @_; print "$_\n" for @y; print "\n"; }
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); foo(@args);
works as expected, but
bar(@args);
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[0], $args[1], $args[2], $args[3]);
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.
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^8: How to return values from a hash?
by perl-diddler (Chaplain) on Apr 21, 2013 at 10:26 UTC |