What is the best way to test an if condition in perl that parameter driven?
For eg: if condition 1 is if($str1 eq “abc”) and condition 2 is if($str2 eq “xyz”), and at runtime the decision is made as to which condition needs to be checked, how would you do it?
$str1 = $ARGV[0];
$str2 = $ARGV[1];
$cond_value = $ARGV[2];
$cond1 = "$str1 eq \"abc\"";
$cond2 = "$str2 eq \"xyz\"";
if($cond_value == 1) {
$return_val = eval($cond1);
}
else {
$return_val = eval($cond2);
}
Doesn’t seem to work?
Your example may be over-distilled. It worked when I tried it, although it’s probably not doing what you intended (and it will fail with strict/warnings, as Justin says). The values of
$str1and$str2are expanded when$cond1and$cond2are assigned, not insideif ($cond_value). That can be fixed by escaping the dollar signs ($cond1 = "\$str1 eq \"abc\"";).evalhas a bunch of issues, though, including the trouble of figuring out the right escapes to use and possible security risks if you’re working with untrusted data. You may want to consider using anonymous subroutines: