Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to check for valid command line parameters?

Tags:

perl

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 < 3) {
  print STDERR "Usage: $0 PATTERN [FILE...]\n";
  exit 1;
}

Is this a valid pattern?

like image 296
helpermethod Avatar asked Feb 16 '11 21:02

helpermethod


People also ask

How do you validate command line arguments in C++?

Show activity on this post. bool isuint(char const *c) { while (*c) { if (! isdigit(*c++)) return false; } return true; } ... if (isuint(argv[1])) ... Additional error checking could be done for a NULL c pointer and an empty string, as desired.

What are command line parameters and how are they passed?

Command line arguments are nothing but simply arguments that are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution.

What is a CMD parameter?

What Is a Command Line Parameter? A command line parameter can be used to enable or disable certain features of a game when the program begins. The most commonly used command line parameter for video games is -console. For many PC games, this command enables the console where additional cheats can be entered.


2 Answers

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};
like image 146
DVK Avatar answered Oct 13 '22 04:10

DVK


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
like image 27
toolic Avatar answered Oct 13 '22 03:10

toolic