Get an input of array using Getoptions in perl

6.4k views Asked by At

I am trying to get create a file in perl using Getoptions and one of the input is an array. My code looks like this:

my $filename = 'grid.sh';
my @job_name;
my $output_file;
my $testbench;
my %opts = (
 'job_name' => \@job_name,
 'output' => \$output_file,
 'testbench' => \$testbench,
);
GetOptions(
  \%opts,
 'job_name=s',
'output=s',
'testbench=s'
);
open(my $fh, '>', $filename) or die "Could not open";
for (my $i=0; $i <= 2; $i++) {
print $fh "Job names are $job_name[$i]";
}
   close $fh;

in my command line I am providing the input as

perl grip_script.pl "-job_name test -job_name test1 -job_name test2"

But the file is not giving the right data. Can you please tell me where I am going wrong?

Thanks

2

There are 2 answers

0
Sam Choukri On

You mistakenly double-quoted your entire list of arguments, thereby making it into a single invalid argument.

Try this instead:

perl grip_script.pl --job_name test --job_name test1 --job_name test2

As bytepusher suggested, you also need to fix your call to GetOptions:

GetOptions(
 'job_name=s' => \@job_name,
 'output' => \$output_file,
 'testbench' => \$testbench,
);

With those two changes, I am able to run your test script and get the expected results.

Output:

Job names are testJob names are test1Job names are test2

Note you are missing a line break in your print statement so all three print calls appear on the same line.

4
bytepusher On

Your notation of GetOpts is confusing to me.

Why do you pass in %opts and then more?

Have you tried this?

GetOptions(
    'job_name=s' => \@job_name,
'output=s' => \$output_file,
'testbench=s' => \$testbench,
);

?

Also, see here in the documentation further examples of multiple values passed in.

Those values only appear if you do not quote in command line, as the other answerer pointed out, so call

perl grip_script.pl --job_name test --job_name test2 --job_name test3

and for me, they are all in @job_name.