I have a statement
$set eq "Y" ? $set = "N" : $set = "Y";
But no matter what it always sets to "N"
# Toggle setting
if ($set eq "Y")
{
$set = "N";
}
else
{
$set = "Y";
}
Why doesn't the one liner seem to work?
9.3. The Binding Operator, =~ Matching against $_ is merely the default; the binding operator (=~) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_.
print() operator – print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) is used as a delimiter to this operator.
Due to precedence rules, perl is not parsing your statement as you think:
$ perl -MO=Deparse,-p -e '$set eq "Y" ? $set = "N" : $set = "Y"'
((($set eq 'Y') ? ($set = 'N') : $set) = 'Y');
-e syntax OK
So as you see, in both conditions, the final result is the $set
scalar which then gets set to Y
.
You can fix it with a few parens:
$set eq "Y" ? $set = "N" : ($set = "Y")
But why repeat the assignment:
$set = $set eq 'Y' ? 'N' : 'Y';
Operator precedence. What you've written is equivalent to
($set eq "Y" ? $set = "N" : $set) = "Y";
If you insist on writing such terse code, this make more sense:
$set = ( $set eq "Y" ? "N" : "Y" );
It's about precedence; let's do the intent with parenthesis, and then let Perl remove them again:
perl -MO=Deparse -e '($set eq "Y") ? ($set = "N") : ($set = "Y"); print $set'
$set eq 'Y' ? $set = 'N' : ($set = 'Y');
print $set;
-e syntax OK
Which is thus the parenthesing required to do as you intended.
If you rather not use "C" style conditional statements, you can do the same thing with 2 lines:
my $set = "Y"; #Set the scope and default value
$set = "N" if ($set eq "Y");
I personally recommend the "C" style described by others above... it easily demonstrates the two options a variable can be.
However, the method I show is great when dealing with a single conditional result.
$set = ($set eq "Y") ? "N" : "Y";
should work
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