Re: fun with hashes!

[email protected] (Uri Guttman) Sat, 24 Nov 2007 12:21:59 -0500
Newsgroups perl.fwp
Message-ID <[email protected]>
>>>>> "DL" == David Landgren <[email protected]> writes:

  DL> 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:

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


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

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

and what if $key is true but not found?? that is a different
problem. your code doesn't handle that, it only handles a false or missing key

  DL> If it does, wait until 5.10 comes out and:

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

same problem.

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

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

there are places where you want to delay the call. you may need to pass
the code ref around or call it multiple times or with different args. i
have found that getting the sub is better as a separate step from
calling it.

uri

-- 
Uri Guttman  ------  [email protected]  -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------  http://jobs.perl.org