SPUG: Slice of HashOfHash

Jacinta Richardson jarich at perltraining.com.au
Fri Nov 17 16:49:42 PST 2006


Ivan Heffner wrote:

> 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.

...

> 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";
>       }
>   }
> 

Or alternately (because there's more than one way to do it:

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

Depending on how the classes are encoded, and whether checking the husband's 
name is going to be a regular enough thing to make it work wrapping into a sub.

I do agree that using || helps, though.  Excellent point!

	J


More information about the spug-list mailing list