Re: fun with hashes!

David Landgren <[email protected]> Sat, 24 Nov 2007 10:43:58 +0100
Newsgroups gmane.comp.lang.perl.fun
Message-ID <[email protected]>
Uri Guttman writes:
>>>>>> "AP" == A Pagaltzis <[email protected]> writes:
> 
>   AP> * Jerrad Pierce <[email protected]> [2007-11-23 22:50]:
>   >> exists( $dispatch{$sub} ) ? $dispatch{$sub}->() :
>   >> warn "Key <$sub> does not exist in the dispatch table";
> 
>   AP>     ( $dispatch{$sub} || sub { warn "no such action '$sub'" } )->();
> 
> some variations on that:
> 
> 	my $sub = $dispatch{$key} or die "trying to call missing code" ;
> 	$sub->() ;
> 
> or:

[...]

> or:
> 
> 	my $sub = $dispatch{ $key } || $dispatch{ 'default' } ;


Why stop there? Assuming $key never evaluates to 0:

   my $sub = $dispatch{ $key || 'default' };

If it does, wait until 5.10 comes out and:

   my $sub = $dispatch{ $key // 'default' };

Although there really is little point stuffing the coderef into a 
scalar, it's not like there's anything you can do to it. It's clearer to 
not draw attention to it and just run the damned thing:

   $dispatch{ $key || 'default' }->();

David