Hellow fellow Monks,
I recently came up with a really weird way to use perl's
hashes. Maybe someone tried it before and found it
usefull or maybe I just came up with the most usless
thing ever ;)
Here is the example code:
#!/usr/bin/perl use warnings; use strict; my %options = ( one => \&one, two => \&two, three => \&three, ); my $ret; # return code from the sub while(chomp(my $opt = <STDIN>)){ if(exists $options{$opt}) { $ret = &{$options{$opt}}; last if $ret == 0; } else { default(); } } sub one { print "one\n"; return 1; } sub two { print "two\n"; return 1; } sub three { print "three and break the loop\n"; return 0; } sub default { print "Default\n"; }
I thought of it as a method to avoid a really long list of
if-elsif-elsif-elsif-elsif-else chain, and as Perlmonks
is full of people that understand perl much better than
I do so I decided to contribute this idea, and would
really like to know your honest opinions on such a weird
hash usage.

Here are the questions:
a) Is it worth using?
b) Is this will be taken as a 'bad style' example?
c) Is if-elsif-elsif-elsif-else chain more efficient than this?

Thank you all for taking the time to read this node.
Regards,
Mulander

In reply to 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.