How can I manage command line arguments / variables for a script written in Perl?

I am trying to manage the numerous arguments the user specified when executing the command. So far, I have been trying to limit my project script to manage arguments as flags, which I can easily deal with Getopt :: Long as follows:

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

This way I can check if a or b were specified, and then execute the appropriate code / functions.

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

command -a black -b white

This is good, but I cannot find a good way to determine if -a or -b is given first. Therefore, I do not know if the argument variable is assigned to $ARGV[0]or $ARGV[1]after execution GetOptions ("a" => \$a, "b" => \$b);.

How can I determine which variable is associated with -aand which is related to -bin the above example?

+3
source share
2 answers

Getopt supports arguments for parameters, 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 the question prints:

a is black and b is white

See the manual page for more information . This is a very powerful module.

+6
source
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 see the perl Getopt :: Long documentation . From this document.

GetOptions() , @ARGV 1, . . true .

, GetOptions() . , . .

GetOptions() . STDERR .

.

+2

Source: https://habr.com/ru/post/1747478/


All Articles