in reply to Re^4: CLI using hashes
in thread CLI using hashes
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.
|
|---|