Question

I use Getopt::Long to get command line options for my perl script. I would like to pass an optional argument to it so that I can do something if a value was specified, and something else if the option was called, but no value was passed.

The script would be invoked like this:

/root/perlscripts/pingm.pl --installdaemon

for no argument specified, and:

--installdaemon=7.7.7.7

for specifying an optional argument.

Then I'd do this:

Getopt::Long::Configure(qw(bundling no_getopt_compat));
GetOptions ('installdaemon:s' => \$daeminstall) or die ("Error in command line arguments\n");

The next step is where I am doubtful.

If I do:

if ($daeminstall) {
        print "I was called!\n";
        $installdaemon=1;
    }

then, that IF block would never be called if the script was called with /root/perlscripts/pingm.pl --installdaemon, because according to perldoc, an optional argument would take '' for a string if no value was specified.

So how can I check whether the option was specified without passing a value?

Était-ce utile?

La solution

Check for defined $daemsintall instead. If it is defined, the corresponding option was specified; now you can compare it to an empty string to see whether or not it was set to some value.

Example (it uses GetOptionsFromString method, but the approach is the same):

use Getopt::Long(qw/GetOptionsFromString/);
my $tag;
GetOptionsFromString('--tag', 'tag:s' => \$tag);
if (defined $tag) {
    if ($tag eq '') {
        $tag = '7.7.7.7';
    }
    print $tag;
}
else {
    print 'No option supplied';
}

And here's IDEOne demo.

Autres conseils

Use the defined built-in function:

use warnings;
use strict;
use Getopt::Long;

my $daeminstall;
GetOptions(
    'installdaemon:s' => \$daeminstall,
) or die;

if (length $daeminstall) {
    print "installdaemon was used, and has a value: $daeminstall\n";
}
elsif (defined $daeminstall) {
    print "installdaemon was used, but has no value\n";
}
else {
    print "installdaemon was not used\n";
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top