I wanted to write a script that checks if 3 variables (A,B,C) are all unique and dont equal each other. I thought of just doing a big if statement like:
if (A != B) && (A != C) && (B != C){
// do function }
I was just wondering if there is another way? Because the code looks kindof clunky. This is in Perl.
Abstracting complicated details (e.g. those that "look clunky") is the point of subs. Move the logic to a sub if you don't like seeing it. Personally, that looks fine for me for three variables.
Note that if you're moving the code to a sub, you might consider using an O(N) algorithm. Your current approach scales poorly (O(N2)).
sub are_distinct {
my %seen;
++$seen{$_} for @_;
return keys(%seen) == @_;
}
Optimized to exit as soon as possible:
sub are_distinct {
my %seen;
for (@_) {
return 0 if $seen{$_}++;
}
return 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With