in reply to CLI using hashes

For one thing, a hash with 20 keys is not really very big at all. Another thing is you shouldn't be iterating on the hash keys and matching with eq. The hash can do near O(1) lookups by itself -- that's one of the major reasons to use a hash. You are completely eliminating that advantage, and you're making the code much more complicated than it needs to be. The entire inside of your while loop can be replaced with this:

chomp; if (exists $myhash{$_}) { $myhash{$_}->(); } else { $myhash{default}->(); }

Update: in case it wasn't clear from my reply, I suggest you stick with the hash-based approach. It should work fine for this kind of thing.

Replies are listed 'Best First'.
Re^2: CLI using hashes
by bahadur (Sexton) on May 30, 2005 at 01:33 UTC
    thanks for the wonderful tip. this was so nice. by the way if 20 commands are not such a big thing than how many commnads will make it big? i am asking so just incase i have to make another hash
      You would need to be well into the tens of thousands of entries before the hash started having problems. And at that point, the problems would be memory-related, not cpu-related, so splitting the hash wouldn't help. In short, you should never need to worry about if a hash is getting too big, up until the point at which you should have your data in a database, anyway.
        ok now my code looks like this
        sub settime($){ print "nMetrics>You have entered the settime command\ +n"; print "nMetrics>The argument given is $_[0]\n" +;} sub showtime{ print "nMetrics>You have entered the show time c +ommand\n";} sub error{ print "nMetrics>Invalid command line options\n";} $myhash{"set time"}=\&settime; $myhash{"show time"}=\&showtime; $myhash{default}=\&error; print "Welcome to nMetrics application monitor\n"; print "Please type in a command\n"; label:print "nMetrics>"; while(<STDIN>) { chomp; if (exists $myhash{$_}) {$myhash{$_}->();} else {$myhash{default}->();} goto label; }
        i cant understand how i am going to pass arguments to my sub routines. can u just specify who i can pass arguments in this sort of a set up?