Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking multiple mutually exclusive options in perl's getopt

Tags:

perl

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.

like image 429
cajwine Avatar asked Oct 08 '22 14:10

cajwine


1 Answers

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.

like image 117
jm666 Avatar answered Oct 13 '22 10:10

jm666