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?
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.
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With