开发者

Easy way to check for valid command line parameters?

I'm looking for an easy way to check for a correct number of command line parameters, displaying a usage message if an error occurs and then immediately exit.

I thought of something like

if (@ARGV 开发者_如何学Go< 3) {
  print STDERR "Usage: $0 PATTERN [FILE...]\n";
  exit 1;
}

Is this a valid pattern?


Also, I would STRONGLY suggest using the idiomatic way of processing command line arguments in Perl, Getopt::Long module (and start using named parameters and not position-based ones).

You don't really CARE if you have <3 parameters. You usually care if you have parameters a, b and C present.

As far as command line interface design, 3 parameters is about where the cut-off is between positional parameters (cmd <arg1> <arg2>) vs. named parameters in any order (cmd -arg1 <arg1> -arg2 <arg2>).

So you are better off doing:

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};


Another common way to do that is to use die

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

You can get more help on the @ARGV special variable at your command line:

perldoc -v @ARGV


Yes, it is fine. @ARGV contains the command-line arguments and evaluates in scalar context to their number.

(Though it looks like you meant @ARGV < 2 or < 1 from your error message.)


Use $#ARGV to get total number of passed argument to a perl script like so:

if (@#ARGV < 4)

I've used before and worked as shown in http://www.cyberciti.biz/faq/howto-pass-perl-command-line-arguments/.

See the original documentation at http://perldoc.perl.org/perlvar.html, it states that:

@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.


You can compare with $#ARGV instead the array @ARGV

if ($#ARGV < 3) { ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜