SPUG: Slice of HashOfHash

Ivan Heffner iheffner at gmail.com
Thu Nov 16 11:24:50 PST 2006

One of the subthreads within this thread has been checking the
defined()ness of a value before doing an equality check in order to
prevent warnings.  The usual approach is this:

  foreach my $key ( keys %HoH ) {
          if($Hoh{$key}{husband} && $HoH{$key}{husband} eq "fred") {
                  print "yes\n";

This is all fine in a simple case, but know that a hash look-up, while
relatively cheap, is not free.  Further, taking this example and
abstracting it into an object-based interface, it become relatively
expensive and incurs useless overhead.

  foreach my $family ( $cartoon->families() ) {
      if ($cartoon->$family->husband() && $cartoon->$family->husband()
eq 'fred') {
          print "yes\n";

This now does a method call to get the family, then another to get the
husband to check if it is "true" then does it all again to check
equality.  In a big app, these calls get expensive.  But there's a
short-cut method to do this.  Use Perl's short-circuiting logical '||'
to make a single method call (or set of method calls):

  foreach my $family ( $cartoon->families() ) {
      if ( ( $cartoon->$family->husband() || '' ) eq 'fred') {
           print "yes\n";

This will only do the method calls once, then use an empty string for
the equality check if there is no husband.

It's a small tweak, but is easier on your CPU and your maintenance developers.

Ivan Heffner
Sr. Software Engineer
DAS Lead

More information about the spug-list mailing list