It has already been mentioned that this is a known and useful technique. A way to improve it further in cases when you don’t actually need these functions elsewhere in the code is to put inline them in the hash assignment as anonymous functions:

my %options = ( one => sub { print "one\n"; return 1; }, two => sub { print "two\n"; return 1; }, three => sub { print "three and break the loop\n"; return 0; }, '' => sub { print "Default\n"; }, );

(I put the default into the hash under the empty string key; the choice of key is arbitrary, it’s just usually a good idea to keep everything together.)

Welcome to the world of first-class functions. :-)

Note also that references are always considered true, so instead of something like

if( exists $dispatch{ $action } ) { $dispatch{ $action }->(); } else { $default->(); }

you can just say

&{ $dispatch{ $action } || $default }();

This lets you simplify your code:

while ( chomp( my $opt = <STDIN> ) ) { &{ $options{ $opt } || $options{ '' } }() or last; }

Also, I notice in your code that you declared $ret outside the loop body. Unless you really need to use it outside the loop (which in your case, with the return code only being 0 or 1 and then only serving for control flow, you obviously don’t), it is good habit to declare it inside the loop instead. Keep variables scoped as tightly as at all possible.

Makeshifts last the longest.


In reply to Re: Hash option/menu loop wierd or usefull? by Aristotle
in thread Hash option/menu loop wierd or usefull? by mulander

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.