in reply to Trying to simulate a CLI using hashes...

I believe this is your problem:

$command_action= $cl[0]{$cl[1]};

In strict, you can't use $cl[0] (contains 'log') as a hash ref (pointing to the %log hash).

As was mentioned before, you should consider using subroutine references instead of eval'ing. As for the problem with two-word commands, I'd suggest this:


%command_list = (
       quit => \&end_program,
       greeting => \&greeting,
       time => \&systime,
       help => \&help,                        
       log => \&which_log   # this one is new
);

sub which_log {
  my $arg = shift;
  return start_logs() if ($arg eq "start");
  return stop_logs() if ($arg eq "stop");
  return log_status();  # default behavior
}

$command = <STDIN>; # assume $command="log start"
@cl = split / /,$command;
my $func = shift @cl;   # first CLI argument is hash key
if (defined($command_list{$func})) {
  $command_list{$func}->(@cl);   # passes rest of CLI args to handler
} else {
  print "invalid command\n";
}


This is untested code, but hopefully it does what I think. Whatever the command line entered, it'll take the first arg as the hashkey in %command_list and pass any extra arguments. So just make a simple wrapper for all your *log() subroutines that uses the argument to determine which to call. Hopefully this makes sense ;)

Replies are listed 'Best First'.
Re: Re: Trying to simulate a CLI using hashes...
by thoth (Novice) on Jan 22, 2002 at 20:12 UTC
    Thanks for the help, I definitly appreciate it. I did have to make a few changes because of newlines, but I believe that is it.
    use strict; my %command_list; my @cl; my $command; %command_list = ( #quit => \&end_program, greeting => \&greeting, #time => \&systime, #help => \&help, log => \&which_log # this one is new ); while (1){ $command = <STDIN>; # assume $command="log start" @cl = split / /,$command; my $func = shift @cl; # first CLI argument is hash key if (!(defined($cl[0]))){ # had to add this to handle single word c +ommands chop($func); } if (defined($command_list{$func})) { $command_list{$func}->(@cl); # passes rest of CLI args to handl +er } else { print "invalid command\n"; } } sub greeting { print "welcome\n" } sub start_logs() { print "Logs Started\n"; } sub stop_logs() { print "Logs Stopped\n"; } sub log_status { print "log status\n" } sub which_log { my $arg = shift; chop($arg); # newline here also... return start_logs() if ($arg eq "start"); return stop_logs() if ($arg eq "stop"); return log_status(); # default behavior }