Reputation: 6093
I am reading through code that looks like
$value = 1.0 - $value if $indx;
but I want it in the form
if ($indx == 0) {
$value = 1.0 - $value;
}
However, the second code sample isn't a correct translation of the first. There should be some operator after the if $indx
statement (I like complete sentences). How can I write the first code sample like the second sample?
Upvotes: 2
Views: 372
Reputation: 132822
You start off with the postfix conditional form:
$value = 1.0 - $value if $indx;
To translate that the block form, you have:
if( $indx ) {
$value = 1.0 - $value
}
Both of these subtract $value
from 1.0 if the value in $indx
is true. In Perl, "true" is anything that is not false, and false is one of these values: 0, '0', the empty string, undef, and the empty list.
You can't test for any particular true value because there are so many of them. The original code wants to execute that expression for any true value.
You can check that you don't have a false value though. Using the numerical not-equal operator will coerce the value of undef to the numeric value 0:
if( $indx != 0 ) {
$value = 1.0 - $value
}
Similarly, you can check that you have a false value and negate that:
if( !($indx == 0) ) {
$value = 1.0 - $value
}
This is why your translation doesn't work. You start by running the code if the value in $indx
is true to running the code if the value if false. You've flipped the test.
But, this is really a lot of work when the postfix conditional (the way that apparently works in the old code) is the Perly way to do it.
You don't say why you want it in another form. Perhaps you are trying to run additional statements. No matter what you want to do, you need to preserve the test.
Upvotes: 6