in reply to Hash option/menu loop wierd or usefull?
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.
|
|---|