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
--fooand--barone 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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With