in reply to how to deal with 20 commands

I don't know if this is the best way (perhaps there's a module to help maintain this kind of thing?), but you could use something like this with an array of the possible commands.. The array lets you fix the order the cmds are checked for (perhaps putting the common ones first), and if you capture in the regex, the captured values will be pased as parameters to the sub when it's invoked. Below is a working proof of concept:
use strict; use warnings; my @CMDS = ( { regex => qr/^cp\s+(\S+)\s+(\S+)/, code => \&do_cp }, { regex => qr/^mv\s+(\S+)\s+(\S+)/, code => \&do_mv }, ); my $input_string = <STDIN>; foreach my $cmd ( @CMDS ){ my @match = ($input_string =~ /$cmd->{regex}/) or next; $cmd->{code}( @match ); } sub do_cp { my $src = shift; my $dest = shift; warn "cp $src $dest"; } sub do_mv { my $src = shift; my $dest = shift; warn "mv $src $dest"; }

Replies are listed 'Best First'.
Re^2: how to deal with 20 commands
by bahadur (Sexton) on May 23, 2005 at 02:45 UTC
    thanks for all the help.
    what i am looking for is some thing which works the same way as the module GetOpt::Long or STD works. they parse the command line swtiches and the programmer doesnt habe to worry about if the switches have been types correctly or not
    so is there some thing which can do the same for commands too?

      You could use Getopt::Long:

      local @ARGV = @_; GetOptions( # . . . ) or warn 'Whatever';

      After Compline,
      Zaxo

        It's a pet peeve of mine that Getopt::Long doesn't accept input from anything but @ARGV. I really hope this changes in Perl6 (and no, not just so that it expects input only from @*ARGS ;-)
      You can, of course, do something crazy, and search for 'shell', or 'interactive' on CPAN - maybe someone's been through this before.. it may also reduce the probability that one day one of your users will type
      innocent 'not_really; rm -rf ~/*'
      and walk away whistling...

      seriously, though, read more; ask only when you can show you've put some effort into it...