Getopt::Long - 如何获取不是选项的脚本参数

Getopt::Long - How to get script arguments that are not options

摘自手册页Getopt::Long:

密码是:

use Getopt::Long;
my $data   = "file.dat";
my $length = 24;
my $verbose;
GetOptions ("length=i" => $length,    # numeric
            "file=s"   => $data,      # string
            "verbose"  => $verbose)   # flag
or die("Error in command line arguments\n");

我这样执行脚本:

./myscript.pl --verbose filename.txt

如何获取参数 filename.txt

@ARGV 中留下了非选项。

这意味着如果它们是文件名,您可以简单地使用 <> 来读取它们。

非选项参数只是留在 @ARGV

our $argument = shift @ARGV;

不过,还有一种更简洁的方法来使用 Getopt。通过将散列引用指定为第一个参数,所有选项都分配给该散列。这是将所有选项放在一个地方的好方法。选项规范可以放入 qw 列表中。

use strict;
use diagnostics;
use Getopt::Long;

## %options must be declared seperately because it is referenced in its own definition
our %options;
%options = (
  # set default debug level
  debug => 0,
  # set default file name
  file => "file.dat",
  # option with multi-effects, setting debug and verbose at once
  quiet => sub { @options{qw/debug verbose/} = (0, 0); },
  loud  => sub { @options{qw/debug verbose/} = (999, 1); },
);

GetOptions(\%options, qw/debug+ verbose! file=s length=o quiet loud/);

our $argument = shift @ARGV;
die "missing first argument\n" unless defined $argument;

print "Starting program [=11=] on $argument\n" if $options{verbose};
if ($options{debug} >= 2) {
  ## Load this module only if we need it, but you must guarantee it's there or trap the error with eval{}
  require Data::Dump;
  printf "Dumping options hash\n%s\n", Data::Dump::pp(\%options);
}

引用原题:

摘自手册页:Getopt::Long

Mixing command line option with other arguments

Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash -- on the command line:

--size 24 -- --all

In this example, --all will not be treated as an option, but passed to the program unharmed, in @ARGV.