Jasio Jasio - 1 month ago 7
Perl Question

How can Perl's Getopt::Long discover arguments with mandatory parameter missing?

In one of my scripts I use the Getopt::Long library. At the beginning of the program I make a call:

&GetOptions ('help', 'debug', 'user=s' => \$GetUser);


The first two arguments are simple: I discover their existance by checking
$opt_help
and
$opt_debug
respectively. However the third argument is tricky, because I need to distinguish between no option at all ($GetUser is undefined, which is ok for me), using "--user" alone (
$GetUser
is also undefined, but this time I want to display an error message) and "--user FooBar" (where the
$GetUser
receives 'FooBar', which I can use in further processing).

How can I distinguish between using no "--user" option and using it alone, without a username?

Answer

You are looking for : instead of =, so 'user:s' => \$GetUser. From Options with values

Using a colon : instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string '' assigned, while numeric options are set to 0

This allows you to legitimately call the program with --user and no value (with = it's an error). Then you only declare my $GetUser; and after the options are processed you can tell what happened. If it is undef it wasn't mentioned, if it is '' (empty string) it was invoked without a value and you can emit your message. This assumes that it being '' isn't of any other use in your program.

Otherwise, when you use 'user=s' and no value is given, the GetOptions reports an error by returning false. I suggest that you always do at least

GetOptions(...)  or die "Option error: $!";

and then you may well leave 'user=s' and rely on the module to catch and report wrong use.

One other way of doing this would go along the lines of

usage(), exit  if not GetOptions('user=s' => \$GetUser, ...);

sub usage { 
    # Your usage message, briefly listing options etc.
}
Comments