using Getopt::Std and Getopt::Long in a Perl script

I have an existing Perl script which has many command line options which are processed using Getopt::Std (getopts function). But, I want to add 2 new options: --testrun and --cfgarray.

I used use Getopt::Long; and GetOptions('testrun' => \$test_flag); "--testrun" takes no argument. I simply used it as a flag like if($test_flag). It works when run separately. But, since in my Perl script there is both use Getopt::Long; and use Getopt::Std;, I get error:

unknown options

from getopts api (when it is called before GetOptions). Can both Getopt::Std and Getopt::Long be used in a single Perl script?

Upvotes: 0

Views: 3118

Answers (2)

haukex
haukex

Reputation: 3013

Getopt::Std and Getopt::Long both just interpret @ARGV, so if you fiddle with that, it's theoretically possible to use both of them in one script, or to call GetOptions more than once. However, I wouldn't recommend it - just use Getopt::Long.

This code:

use Getopt::Std;
getopts('a:b', \my %opts) or die "Bad options\n";

can be translated into:

use Getopt::Long;
GetOptions(\my %opts, 'a=s', 'b') or die "Bad options\n";

and then you can add more options, and long options. Here, I've added a short alias -t for the option --testrun, just to demonstrate:

use Getopt::Long;
GetOptions(\my %opts, 'a=s', 'b',
    'testrun|t', 'cfgarray' ) or die "Bad options\n";

Upvotes: 4

marderh
marderh

Reputation: 1256

AFAIK you cannot use both, but Getopt::Long supports also short options, so you could stick with it.

Upvotes: 1

Related Questions