3

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

jaypal singh
  • 74,723
  • 23
  • 102
  • 147
Rod
  • 61
  • 4
  • 4
    If you're using GetOpt::Long: http://search.cpan.org/~jv/Getopt-Long-2.42/lib/Getopt/Long.pm#Options_with_multiple_values This will allow each `--coords=...` to be added to an array that holds all of them, which you can then iterate over. – DavidO Aug 17 '14 at 05:24

1 Answers1

9

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
Miller
  • 34,962
  • 4
  • 39
  • 60