3
votes

In Perl getopts, is it possible to use the same option multiple times but with different values ? I want to give the user the option of entering different grid coordinates but uses the same option name to minimize confusion.

Ex:

my_grid.pl --coords=10,12 --coords=-18,30 --coords=4,-25

The script would then perform a set of actions on those different pairs. There will always be at least one pair but there is no knowing how many pairs from situation to situation.

I would like to avoid: --coords1= --coords2= --coords3= and so on. I do not know how to deal with the unknown quantity of coords pairs with that 1 and 2 and 3 method anyway. I have used getopts in previous projects but am getting into more complex demands/issues. I tried to search for solutions/examples but probably used the wrong keywords. Thnx for any assist.

Rod

1
If you're using GetOpt::Long: search.cpan.org/~jv/Getopt-Long-2.42/lib/Getopt/… This will allow each --coords=... to be added to an array that holds all of them, which you can then iterate over. - DavidO

1 Answers

9
votes

As documented in Getopts::Long - Options with multiple values:

#!/usr/bin/perl
use strict;
use warnings;

use Getopt::Long;

GetOptions(
    "coords=s" => \my @coords,
);

print "$_\n" for @coords;

Executed using:

my_grid.pl --coords=10,12 --coords=-18,30 --coords=4,-25

Outputs:

10,12
-18,30
4,-25