in reply to Benifits of using hash rather than number of variables?
The three big advantages of passing hashes / hashrefs to your subroutines are:
- you have named parameters inside the subroutine, and you don't have to remember the order of arguments outside the subroutine;
- much easier to handle optional arguments, and to calculate which arguments to pass at runtime;
- easy to build up that hash a little bit at a time;
The big disadvantage of using hashes is that you lose some strictness checking. use strict will usually tell you if you mis-type a variable name, but it can't tell you if you mis-type a hash key - instead, if you mis-type a key name when reading the hash, it'll just auto-vivify. This sort of bug can be a real pain in the arse to track down.
Thankfully, there's a solution to this problem on the CPAN. Tie::Hash::Vivify is meant to let you provide "a hash where if you read a key that doesn't exist, it will call a code reference to fill that slot with a value", but it can of course be used thus:
use Tie::Hash::Vivify; use Carp qw(confess); use Data::Dumper; ... my $hashref = Tie::Hash::Vivify->new(sub { confess("No auto-vivifying!\n".Dumper(\@_)) });
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Benifits of using hash rather than number of variables?
by duelafn (Parson) on Jul 20, 2011 at 14:45 UTC | |
by JavaFan (Canon) on Jul 21, 2011 at 13:39 UTC | |
by duelafn (Parson) on Jul 21, 2011 at 14:33 UTC | |
by JavaFan (Canon) on Jul 21, 2011 at 14:59 UTC | |
by duelafn (Parson) on Jul 21, 2011 at 15:27 UTC | |
by Anonymous Monk on Jul 21, 2011 at 16:51 UTC |