Issues with getopts in perl

Viewed 216

I'm using Getopt::Std to process my command line args. My command line args are strings. I have issuewithgetopts()`, as it works only for single character based opts.

As seen below "srcdir" "targetdir" options are mandatory and script should error out if any one of them is missing. "block" is NOT a mandatory option.

I don't see %options has is being set with the code below, and all my options{key} are NULL. Had I replaced "srcdir=>s" and "targetdir=>t" then the below piece of code works. It doesn't work with "-srcdir" "-targetdir" options. What's the best way to address the issue I have?

Use mode:

perl test.pl -srcdir foo1 -targetdir hello1

#!/usr/bin/perl -w

use strict;
use Getopt::Std;

# declare the perl command line flags/opt we want to allow
my %options=();
my $optstring = 'srcdir:targetdir:block';
getopts( "$optstring", %options);

# test for the existence of the opt on the command line.
print "-srcdir $options{srcdir}\n" if defined $options{srcdir};
print "-targetdir $options{targetdir}\n" if defined $options{targetdir};
print "-blocks $options{block}\n" if defined $options{block};


# other things found on the command line
print "loop:\n" if ($#ARGV > 0);
foreach (@ARGV)
{
  print "$_\n";
}
1 Answers

You really want to use Getopt::Long to handle words like srcdir:

use warnings;
use strict;
use Data::Dumper;
use Getopt::Long;

$Data::Dumper::Sortkeys=1; 

my %options;
GetOptions(\%options, qw(srcdir=s targetdir=s block));

print Dumper(\%options);
print Dumper(\@ARGV);

The reason your hash was empty was that you need to pass a reference to a hash, as shown in Getopt::Std:

getopts( "$optstring", \%options);

Also, since Std only handles single letters, it would interpret srcdir as 6 separate options: s, r, etc.

Related