Search code examples
perlgetopt-long

How to check if only one variable of three is set


I would like to restrict the user to inputting (through Getopt::Long) only one value out of a possible three. The values are 'pc-number', 'ip-address', and 'surname'.

When there were two values, I was doing the following:

if ((!$pc_number and !$address) or ($pc_number and $address)) {
    pod2usage("You must supply pc_number OR ip_address.");
    exit;
} elsif ($pc_number) {
    (do stuff)
}

How can I simply make sure only one out of three variables are set by the user?


Solution

  • Count the number of true values using grep. Could also check for defined if that was appropriate:

    if ( 1 != grep {$_} ( $pc_number, $address, $surname ) ) {
        pod2usage "You must supply one and only one parameter: pc_number, ip_address, surname.";
        exit;
    
    } elsif ($pc_number) {
        ...;