views:

134

answers:

2

I am trying to manage numerous arguments that are specified by a user when they execute a command. So far, I have been trying to limit my script design to manage arguments as flags that I can easily manage with Getopt::Long as follows:

GetOptions ("a" => \$a, "b" => \$b);

In this way I can check to see if a or b were specified and then execute the respective code/functions.

However, I now have a case where the user can specify two arguments variables as follows:

command -a black -b white

This is fine, but I cannot come up with a good way to determine whether -a or -b is specified first. Therefore I do not know whether the argument variable is assigned to $ARGV[0] or $ARGV[1] after I have executed GetOptions ("a" => \$a, "b" => \$b);.

How can I tell which variable is associated with -a and which is associated with -b in the example above?

+7  A: 

Getopt supports arguments to options, so you can say for example:

GetOptions( 'a=s' => \$a, 'b=s' => \$);
print "a is $a and b is $b";

with the command line in your question prints:

a is black and b is white

See the manual page for tons more options. It is a very powerful module.

Tore A.
+3  A: 
my $a = ''; # option variable with default value (false)
my $b = ''; # option variable with default value (false)

GetOptions ('a' => \$a, 'b' => \$b);

print "a is $a and b is $b\n

Please go through the perl documentation of Getopt::Long. From this doc.

The call to GetOptions() parses the command line arguments that are present in @ARGV and sets the option variable to the value 1 if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called enabling the option.

The option name as specified to the GetOptions() function is called the option specification. Later we'll see that this specification can contain more than just the option name. The reference to the variable is called the option destination.

GetOptions() will return a true value if the command line could be processed successfully. Otherwise, it will write error messages to STDERR, and return a false result.

Also this can also help you.

Space