所以,我已经阅读了一些关于如何使用Getopt::Long
和类似的库来处理argv
选项的指南,但由于完全不清楚(对我来说)文档和指南,仍然不知道如何正确使用它。
我有一个脚本。它有下一个参数:-qp
,-pr
,-rp
,-vr
,其中大多数是用于文件名的。
目前我有这种用途Getopt::Long
,我觉得这不合适,因为我每次都需要检查选项之后的内容:
for(my $i = 0; $i < @ARGV; $i+=2){
if ($ARGV[$i] eq "-qp"){
unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
$query_params = $ARGV[$i+1];
}
}
elsif ($ARGV[$i] eq "-pr"){
unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
$params = $ARGV[$i+1];
}
}
elsif ($ARGV[$i] eq "-vr"){
unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-rp"){
$variables = $ARGV[$i+1];
}
}
elsif ($ARGV[$i] eq "-rp"){
unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-vr"){
$replace = $ARGV[$i+1];
}
}
}
也许我不需要为Unix
使用精确的Getopt
库,我只需要将一些args
传递给脚本。有没有办法让它更简单和正确?
与你的说法相反,你没有使用Getopt::Long。但你应该!
use strict;
use warnings qw( all );
use feature qw( say );
use File::Basename qw( basename );
use Getopt::Long qw( );
my %opts;
sub parse_args {
%opts = ();
Getopt::Long::Configure(qw( posix_default ));
GetOptions(
'help|h|?' => &help,
'qp:s' => $opts{qp},
'pr:s' => $opts{pr},
'rp:s' => $opts{rp},
'vr:s' => $opts{vr},
)
or usage();
}
parse_args();
使用:s
而不是=s
会使选项的参数根据注释中的要求可选。
完成上述操作的示例帮助程序子:
sub help {
my $prog = basename($0);
say "usage: $prog [options]";
say " $prog --help";
say "";
say "Options:";
say " --qp path ...explanation...";
say " --qp ...explanation...";
say " --pr path ...explanation...";
say " --pr ...explanation...";
say " --rp path ...explanation...";
say " --rp ...explanation...";
say " --vr path ...explanation...";
say " --vr ...explanation...";
exit(0);
}
sub usage {
my $prog = basename($0);
warn(@_) if @_;
warn("Try `$prog --help' for more informationn");
exit(1);
}
Getopt::Long
文档中的一个快速示例。
现在,您可以使用script --qp=file1 --pr=file2 --rp=file2
调用此脚本
Getopt:Long
为您做的是整理命令行上给出的值,以使其放置它们,以及一些基本的验证(此处=s
意味着您期待一个字符串)。
例如,如果要检查给定文件是否存在,则需要手动执行此操作。
use strict;
use warnings;
use Getopt::Long;
my ($qp,$pr,$rp);
my $verbose;
GetOptions (
"qp=s" => $qp,
"pr=s" => $pr,
"rp=s" => $rp,
"verbose" => $verbose,
) or die "Error in command line arguments";
print "Being verbose.n" if $verbose;
# Quick check all are there if they're all required (?)
die "qp,pr and rp are required!" if grep{ !$_ }($qp,$pr,$rp);
for my $fn ( $qp,$pr,$rp ){
die "Cannot find file '$fn'" unless -f $fn;
}
print "you've given: qp $qp, pr $pr, rp $rp.n";