The trinary is semantically just an if expression though. Perl inherits C's problem that `if` can't be used in an expression context:
my $x = if ($cond) { 1 } else { 2 }; # Syntax error
Because of this, Perl introduces a second syntax to plug the gap: my $x = $cond ? 1 : 2;
That expression is neither obtuse nor hard to read.Something like the code below is hard to read:
my $fee =
$is_member
? ($is_student ? $student_member_fee : $member_fee)
: ($is_student ? $student_fee : $standard_fee);
It's equivalent to the following code that uses `if`: my $fee;
if ($is_member) {
if ($is_student) {
$fee = $student_member_fee;
}
else {
$fee = $member_fee;
}
}
else {
if ($is_student) {
$fee = $student_fee;
}
else {
$fee = $standard_fee;
}
}
But ideally you would want to write this: my $fee =
if ($is_member) {
if ($is_student) {
$student_member_fee
}
else {
$member_fee
}
}
else {
if ($is_student) {
$student_fee
}
else {
$standard_fee
}
};
Though, of course, perl5 doesn't allow that.
You misunderstand. I didnt need an explanation of how they worked. Im refuting that they are a good practice.
I was complaining of the "cleverness" of them, when working or analyzing a codebase with people swapping from if/else loops to trinaries.
I prefer clarity and a bit more verbosity than a per5-ism. If that means a 5 line loop that I can easily follow, then so be it. 1 liners that effectively say "lookie at me im a l33t developer" are a very bad code smell, and make maintenance harder each cycle of more cleverness.
Trinary expressions are supported in a lot of languages. I actually agree with your point about "clever" code but I don't think trinary expressions are clever. They are quite normal and fairly common.
And every language has its idioms that are incomprehensible until you learn them. This isn't clever code so much as shorthand for common things.