Checking multiple mutually exclusive options in perl getopt

How to check what is defined by only one of -a or -b or -c ?

So, not together -a -b , neither -a -c , nor -b -c , nor -a -b -c .

Now

 use strict; use warnings; use Carp; use Getopt::Std; our($opt_a, $opt_b, $opt_c); getopts("abc"); croak("Options -a -b -c are mutually exclusive") if ( is_here_multiple($opt_a, $opt_c, $opt_c) ); sub is_here_multiple { my $x = 0; foreach my $arg (@_) { $x++ if (defined($arg) || $arg); } return $x > 1 ? 1 : 0; } 

The above works, but not very elegantly.

There is a similar question here, but this is different, because checking two exclusive values ​​is easy - but here are a few.

+4
source share
2 answers

Or you can:

 die "error" if ( scalar grep { defined($_) || $_ } $opt_a, $opt_b, $opt_c ) > 1; 

grep in a scalar context returns the number of matched elements.

+2
source
 sub is_here_multiple { ( sum map $_?1:0, @_ ) > 1 } 

sum provided by List :: Util .


Oh right, grep counts in a scalar context, so all you need is

 sub is_here_multiple { ( grep $_, @_ ) > 1 } 
+1
source

All Articles