GetOptions() in perl does not validate full argume

2019-09-15 07:54发布

问题:

Suppose I want to enter 2 command line parameters - source and destination. GetOptions allows the command line by checking only the first character of the argument name instead of the full string. How do I validate for the full arguments strings instead of just allowing its substrings to be passed?

Here's an example program:

my ($source,$dest);
GetOptions(
'from=s' => \$source,
'to=s' => \$dest
) or die "Incorrect arguments\n";

It accepts any of:

  • -from
  • -fro
  • -fr
  • -f

  • -to

  • -t

However, I want it to accept only

  • -from
  • -to

and fail if anything except those full words is passed.

How can I disallow the abbreviated options?

回答1:

By default, abbreviations are enabled. Disable auto_abbrev. Refer to Getopt::Long:

use warnings;
use strict;
use Getopt::Long qw(:config no_auto_abbrev);

my ($source,$dest);
GetOptions(
'from=s' => \$source,
'to=s' => \$dest
) or die "Incorrect arguements\n";

For example, when -fro is passed, this dies with the message:

Unknown option: fro
Incorrect arguements


回答2:

See "Configuring Getopt::Long" in the documentation:

auto_abbrev

Allow option names to be abbreviated to uniqueness. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case "auto_abbrev" is disabled.