1

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?

toolic
  • 57,801
  • 17
  • 75
  • 117
unclemeat
  • 5,029
  • 5
  • 28
  • 52

2 Answers2

5

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) {
    ...;
Miller
  • 34,962
  • 4
  • 39
  • 60
2

This seems to do it:

if (($x xor $y xor $z) and not $x && $y && $z) {
    ... # one (and only one) is true
}

...although I'm not sure it's the kind of thing you'd want to encounter in code you have to maintain.

Jim Davis
  • 5,241
  • 1
  • 26
  • 22
  • This is a good solution. I agree it's a little convoluted, but a comment makes the intent pretty obvious. Thank you very much. – unclemeat Oct 30 '14 at 07:11
  • 1
    This does work in this specific case, but it's not expandable. Meaning, if there were 4 values, this style would return true if 3 of them were true. – Miller Oct 30 '14 at 07:39
  • 1
    Yeah, I don't know what I was thinking when I wrote this. – Jim Davis Oct 30 '14 at 11:52