Since you have 'commands' that are more than one 'word', you are going have trouble deciding how to split your user commands from your user arguments.

One idea would be to build a regex from the keys of your command hash, which splits the command from the remainder, then pass that remainder to the dispatch table:

# in init phase: my $commands = join "|", keys %myhash; my $command_regex = qr/^($commands)\s*(.*)$/i; # in input loop: while(<STDIN>) { if ( m/$command_regex/o ) { my $command = lc $1; $myhash{ $command }->( $2 ); } else { $myhash{"error"}->( $_ ); } }

But I think that a much better idea is to make 'set' and 'show' top-level commands with a list of variables that they can set and show. Then a simple m/^(\w+)\s+(.*)$/i can split your commands from arguments, then test $1 for definedness as before, and feed in $2 as args.

Some nits: If "default" is an error, then I would call it "error". Also, %myhash is a terrible name for a variable.


In reply to Re^5: CLI using hashes by fishbot_v2
in thread CLI using hashes by bahadur

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.