English 中文(简体)
检查有效命令行参数的简单方法?
原标题:Easy way to check for valid command line parameters?
  • 时间:2011-02-16 21:30:42
  •  标签:
  • perl

我正在寻找一种简单的方法来检查命令行参数的正确数量,如果出现错误,显示使用消息,然后立即退出。

我想了一些类似的事情

if (@ARGV < 3) {
  print STDERR "Usage: $0 PATTERN [FILE...]
";
  exit 1;
}

这是一个有效的模式吗?

最佳回答

此外,我强烈建议使用Perl中处理命令行参数的惯用方法,Getopt::Long模块(并开始使用命名参数,而不是基于位置的参数)。

如果你有<;3个参数。您通常关心是否存在参数a、b和C。

就命令行接口设计而言,3个参数是关于位置参数(cmd<;arg1>;<;arg2>;)与任何顺序的命名参数(cmd-arg1<;arg1>;-arg2<;arg2>;)之间的界限。

所以你最好做:

use Getopt::Long;
my %args;
GetOptions(\%args,
           "arg1=s",
           "arg2=s",
           "arg3=s",
) or die "Invalid arguments!";
die "Missing -arg1!" unless $args{arg1};
die "Missing -arg2!" unless $args{arg2};
die "Missing -arg3!" unless $args{arg3};
问题回答

另一种常见的方法是使用死亡

die "Usage: $0 PATTERN [FILE...]
" if @ARGV < 3;

您可以在命令行中获得有关@ARGV特殊变量的更多帮助:

perldoc -v @ARGV

是的,很好@ARGV包含命令行参数,并在标量上下文中计算它们的数字。

(尽管看起来您的意思是错误消息中的@ARGV<;2<;1。)

使用$#ARGV获取传递给perl脚本的参数总数,如下所示:

if (@#ARGV < 4)

我以前使用过,并按照http://www.cyberciti.biz/faq/howto-pass-perl-command-line-arguments/

请参阅http://perldoc.perl.org/perlvar.html,其中规定:

@ARGV公司

The array @ARGV公司 contains the command-line arguments intended for the script. $#ARGV is generally the number of arguments minus one, because $ARGV[0] is the first argument, not the program s command name itself. See $0 for the command name.





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签