in reply to Advantages to passing a hash to a subroutine?
If the sub takes a lot of arguments (more than one or two), then passing a hash can be a lot more readable.
perform_wedding($smith, $jones, $brown);
Which one's the husband, which is the wife, and who is performing the ceremony?
perform_wedding( official => $smith, wife => $jones, husband => $brown, );
Ah, that's better!
Another advantage, for subs which are intended to be called as methods (in an object oriented design), is it allows subclasses to easily override methods, taking additional parameters without disturbing the superclass. e.g.
Imagine we have:
my $venue = Wedding::Venue->new; $venue->perform_wedding($smith, $jones, $brown);
And we have a subclass Elvis::Wedding::Venue for a venue which offers Elvis-themed weddings. It takes an extra parameter which says what song is sung at the ceremony...
my $venue = Elvis::Wedding::Venue->new; $venue->perform_wedding($smith, $jones, $brown, "Hound Dog");
Now, a new version of Wedding::Venue is released which takes a fourth parameter for the date of the wedding...
my $venue = Wedding::Venue->new; $venue->perform_wedding($smith, $jones, $brown, '2012-06-18');
... and suddenly there's a conflict over that last parameter. This becomes a lot safer with named parameters.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Advantages to passing a hash to a subroutine?
by alliswell (Novice) on Jun 18, 2012 at 21:43 UTC |