Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask for one argument out of two using GetOptions?

I am trying to create a CLI script in perl that accepts multiple CLI args. I'm parsing these arguments using the GetOptions function. I have 2 options --foo and --bar one of which exactly one has to be present with the corresponding value passed to it.

Is there a way to handle this directly in GetOptions? or do I have to manually write the check for this?

I'm using the Getopt::Long module.

EDIT: When I said:

I have 2 options --foo and --bar one of which exactly one has to be present with the corresponding value passed to it.

I meant to say that these should be CLI arguments to be used as either:

$ perl my-cli-script.pl --foo somevalue
$ #Or
$ perl my-cli-script.pl --bar someothervalue

but not

$ perl my-cli-script.pl --foo somevalue --bar someothervalue
$ #or
$ perl my-cli-script.pl
like image 583
ayushgp Avatar asked Sep 15 '25 03:09

ayushgp


1 Answers

Just check afterwards.

GetOptions(
   "help|h|?" => \&help,
   "foo=s"    => \$opt_foo,
   "bar=s"    => \$opt_bar,
)
   or usage();

defined($opt_foo) || defined($opt_bar) )
   or usage("Must specify --foo or --bar");

!( defined($opt_foo) && defined($opt_bar) )
   or usage("Can't specify both --foo and --bar");

@ARGV == 0
   or usage("Too many arguments");

Sample usage:

sub usage {
   if ( my ($msg) = @_ ) {
      chomp($msg);
      warn("$msg\n");
   }

   my $prog = basename($0);
   warn("Try `$prog --help' for more information.\n");
   exit(1);
}
like image 56
ikegami Avatar answered Sep 17 '25 18:09

ikegami