Reputation: 275
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?
Upvotes: 3
Views: 635
Reputation: 66883
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 to0
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 and emits a descriptive message to STDERR
. So you may well leave it and do
GetOptions( 'user=s' => ...) or die "Option error\n";
and rely on the module to catch and report wrong use. Our own message above isn't really needed as module's messages clearly describe the problem.
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.
}
I'd like to add – you don't need &
in front of a function call. It makes the caller's @_
visible, ignores function prototype, and does a few other similarly involved things. One common use is to get a coderef, $rc = \&fun
, where it is needed. See for example this post
Upvotes: 8