I have this code
#!/usr/bin/perl
use warnings;
use strict;
my $nis = "qqq";
my $grp = "pre-qqq";
if ($nis eq $grp || 'pre-' . $nis eq $grp) {
print "match1\n";
}
if (($nis || 'pre-' . $nis) eq $grp) {
print "match2\n";
}
where the first if-statement works, but the second doesn’t.
What is wrong with the second?
Can it be done without repeating the variables twice?
Because the first makes (potentially) two comparisons, first comparing
$nisto$grpand, if that fails, comparing'pre-'.$nisto$grp, while the second will only ever make a single comparison, of$nis || 'pre-'.$nisagainst$grp.Your problem is that
$nis || 'pre-'.$nisis not a quantum superposition which can take either value depending on how you look at it, it is a single value of either$nisor'pre-'.$nis. If$nisis truthy (which is to say, it is not an empty string, undef, the number 0, or the string “0”), then that value will be$nis. If not, that value will be'pre-'.$nis(which, given the truthiness rules, means that'pre-'.$niswill only ever be either'pre-'or'pre-0').If you want to compare against two values, you generally need to make two comparisons… but you can do this particular comparison in one step by making the value you test against a regular expression:
I’d stick with the with your first comparison, though, for the sake of readability.