Prakhar Shukla
Prakhar Shukla

Reputation: 9

How to take list as an input in command line option format in Perl

I am trying to take a list from the user, using command line options for the input. The perl script is shown below. Here Input 3 must be a list provided from shell. I don't know what should I put in there for a list, hence used a string.

my %Inputs =(
  "Company_name=s"        =>\my $Input1,
  "Place=s"               =>\my $Input2,
  "Revenue=s"             =>\my @Input3,
  "No_of_Employee=i"      =>\my $Input4,
);

These Inputs are then used inside a subroutine

subroute ($Input1, $Input2, @Input3, $Input4);

The command line format for input is

./my.pl -Input1 user/file1 -Input2 user/file2 -Input3 ...

I don't know how and what format I should enter the list in command line. And also while taking list as input what should i specify it as string (s) or what for a list.

Upvotes: 0

Views: 568

Answers (1)

simbabque
simbabque

Reputation: 54373

It looks like you are using Getopt::Long. The docs about repeating arguments give multiple ways of doing this.

The way you've written your code lets you repeat the same argument multiple times.

GetOptions( "foo=s" => \my @foo);
print Dumper \@foo;

# $ ./bar.pl --foo hello --foo world
# [ "foo", "bar" ]

Alternatively you can make it take multiple values on the same option.

GetOptions( "foo={,}" => \my @foo);
print Dumper \@foo;

# $./bar.pl --foo hello world "how are you?"
# [ "foo", "bar", "how are you?" ]

The {,} means it needs zero or more inputs, making it optional. It's similar to regex quantifiers. You can also do:

  • {2} - exactly two
  • {2,} - two or more
  • {2,4} - between two or four

Upvotes: 3

Related Questions