First, if you start your variables with undef
, then you can tell if they were on the command line by checking after you process the command line arguments. An optional value ends up as the empty string if the option was specified without a value. You can make an option take an optional value with :
instead of =
(which makes it a mandatory value):
use v5.12;
use Getopt::Long;
my $loc;
my %opts = (
"location:s" => \$loc,
);
GetOptions( %opts ) or die( "Parameter is not exist" );
say "Location is defined" if defined $loc;
say "Location is $loc";
A few runs:
$ perl test.pl --location /a/b/c
Location is defined
Location is /a/b/c
$ perl test.pl --location
Location is defined
Location is
$ perl test.pl
Location is
I couldn't discern if you wanted to set a default value of 1. You can use a code reference to modify the value if it's the empty string:
use v5.12;
use Getopt::Long;
#file testing.pl
my $abc;
my $loc;
my %opts = (
"location:s" => sub { $loc = $_[1] ne '' ? $_[1] : 1 },
);
GetOptions( %opts ) or die( "Parameter is not exist" );
say "Location is $loc";
Some runs:
$ perl test.pl --location
Location is 1
$ perl test.pl --location /a/b/c
Location is /a/b/c
$ perl test.pl
Location is
UPDATE
Here's the program which adds in another option. This isn't a problem.
use v5.12;
use Getopt::Long;
my $test;
my $loc;
my %opts = (
"location:s" => sub { $loc = $_[1] ne '' ? $_[1] : 1 },
"test" => \$test,
);
GetOptions( %opts ) or die( "Parameter is not exist" );
say "Location is $loc";
say "Test is $test";
And some runs, where I can't reproduce your claim:
$ perl test.pl --location /a/b/c --test
Location is /a/b/c
Test is 1
$ perl test.pl --location --test
Location is 1
Test is 1