-   Programming (
-   -   Problem with passing arguments in Perl (

bahadur 05-29-2005 11:36 PM

Problem with passing arguments in Perl
I am trying to make CLI. when the script starts the user will type in some command and script performs the required action.

i have used hashes for purpose of efficiency. what i do is that the command is the key of the hash and the value of the hash is a reference to a sub routine.

now i cant figure out how to pass arguments to such functions.

here is my code


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 command\n";}
        sub error{ print "nMetrics>Invalid command line options\n";}

        $myhash{"set time"}=\&settime;
        $myhash{"show time"}=\&showtime;

        print "Welcome to nMetrics application monitor\n";
        print "Please type in a command\n";

        label: print "nMetrics>";
                if (exists $myhash{$_})

        goto label;

now with this code i can only type in a command. if the user also has to pass some arguments with the command i cant do that.

how will i pass arguments to my sub routines?

puffinman 05-30-2005 01:47 AM

Mayhap something like this?


while (1) {

  chomp($input = <STDIN>);

  # this splits the input on whitespace
  @args = split /\s+/, $input;

  # the first argument should have been the command
  $cmd = shift @args;

  # do whatever with $cmd and @args...
  $coderef = $myhash{$cmd};

  if ($coderef and @args) {
    # valid command with args
  } elsif ($coderef) {
    # valid command, no args
  } else {
    # invalid command


I'm thinking you could also just go ahead and pass the @args array even if it's empty; an empty list should look the same to the called function as no arguments at all.

All times are GMT -5. The time now is 03:11 AM.