5

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

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

Now have

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 is working, but not very elegant.

Here is the similar question already, but this is different, because checking two exclusive values is easy - but here is multiple ones.

Community
  • 1
  • 1
cajwine
  • 3,100
  • 1
  • 20
  • 41

2 Answers2

3

Or you can:

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

The grep in scalar context returns the count of matched elements.

clt60
  • 62,119
  • 17
  • 107
  • 194
  • 1
    The `>` enforces scalar context anyway, and there is no need for the `defined` check, so this could be `die "error" if grep($_, $opt_a, $opt_b, $opt_c) > 1` – Borodin Jun 10 '12 at 12:38
1
sub is_here_multiple { ( sum map $_?1:0, @_ ) > 1 }

sum is provided by List::Util.


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

sub is_here_multiple { ( grep $_, @_ ) > 1 }
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • it throwing "syntax error at xx line 9, near "sum map". "sum" - comes from where? perldoc -f sum don't know it. – cajwine Jun 10 '12 at 07:33
  • 2
    Says the person loading Carp. Which one do you think is a "big module". Anyway, feel free to write your own `sum`. – ikegami Jun 10 '12 at 07:35