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(\@_))
});
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|