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



取自手册页面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 argumentsn");

我这样执行脚本:

./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 argumentn" unless defined $argument;
print "Starting program $0 on $argumentn" 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 hashn%sn", Data::Dump::pp(%options);
}

引用原始问题:

取自手册页面:Getopt::Long

将命令行选项与其他参数混合

通常程序采用命令行选项以及其他参数,例如文件名。最好始终指定选项在前,其他参数在后。CCD_ 6将,但是,请允许选项和参数混合使用并"过滤掉"在将其余参数传递给程序要停止Getopt::Long处理进一步的参数,在命令行上插入双短划线:

--size 24 -- --all

在本例中,--all不会被视为一个选项,而是传递给程序在@ARGV中未受伤害。

最新更新