Sruthi Subramanyam
Sruthi Subramanyam

Reputation: 41

Multiple command line arguments in perl when one argument mistakenly takes other argument as its value

I am working on a perl program (perl 5.8). This program uses command line arguments for its inputs. The problem I face is this - I am using multiple command line arguments. E.g.

tool -f "arg1_val" -p "arg2_val"

But in cases when user forgets to specify a value say

tool -f -p "arg2_val"

Instead of erroring out, it assumes -f = -p

I am using Getopt::Long and the routine GetOptions

GetOptions ("f=s" => \$opt_f,
            "p=s" => \$opt_p,
           );

Upvotes: 3

Views: 281

Answers (2)

Arunesh Singh
Arunesh Singh

Reputation: 3535

You should use : instead of =.

You should check "Summary of Option Specifications" in Getopt::Long. This is from GetOptions.

=s: Option takes a mandatory string argument. This string will be assigned to the option variable. Note that even if the string argument starts with - or --, it will not be considered an option on itself.

:s: Option takes an optional string argument. This string will be assigned to the option variable. If omitted, it will be assigned "" (an empty string). If the string argument starts with - or --, it will be considered an option on itself.

Below should work. If you ommit any argument, the corresponding variable will be assigned "".

GetOptions ('f:s' => \$opt_f,
            'p:s' => \$opt_p,
           ) or die("Error in command line arguments\n");

# later you can check for argument variable if any option is mendatory for you.
die "No value passed to -f\n" unless($opt_f);

Upvotes: 4

choroba
choroba

Reputation: 241858

What error would you expect? The -f option has an argument, and the -p option wasn't specified. You have to handle mandatory or extra options yourself:

die "Missing -p\n" unless defined $opt_p;
die "Missing -f\n" unless defined $opt_f;
die "Extra arguments @ARGV\n" if @ARGV;

Upvotes: 0

Related Questions