Chaining ternary operators (raising awareness / mini-lesson )

I notice that LLMs have a strange way of writing perl.
(strange until you learn it !)

Chaining ternary operators
these seem to be used in places where i would have been more familiar with a simple if/then/else conditional. This one‑liner is useful when you need to assign a value based on a series of mutually exclusive tests without writing explicit if/elsif/else blocks.

Chaining ternary operators for compact conditionals

my $age = 27;       
      
my $category = $age < 13          ? 'child'        
                          : $age < 20          ? 'teen'     
                          : $age < 65          ? 'adult'      
                          :                            'senior';      
       
print "Category: $category\n";           
# Determine a short label for a set of unrelated inputs         
my $label = $age < 13            ? 'child'       
          : $color eq 'red'              ? 'stop'         
          : $count == 0                  ? 'empty'        
          : $mode eq 'debug'        ? 'verbose'         
          : $size > 1000                 ? 'big'         
          : 'default';          
  • When condition is true, the part after the question‑mark, becomes the value of the whole expression.
  • if true, The rest of the chain (other ternary tests) are never evaluated. also including the last return value is also skipped, in this case.
  • therefore, ordering matters.
  • finally, The final : supplies the fallback value, acting as the “else” case.
  • you must be able to read it easily, but it provides terse syntax.
  • Alternatives: if this isnt appropriate for your usecase, then alternatives are: given/when, hash lookup, or simple if/else .

an extra value can be appended to the right side to return a specific false value.
otherwise, it is implied that testing false will be handled/passed by/to the next ternary in the chain.

use strict;
use warnings;

my $score = 78;          # try different values

my $result =
    $score >= 90 ? 'A: Excellent' :
    ( $score < 90 ? 'Not an A, keep trying' :
      $score >= 80 ? 'B: Good' :
      ( $score < 80 ? 'Not a B, try harder' :
        $score >= 70 ? 'C: Satisfactory' :
        ( $score < 70 ? 'Not a C, improve' :
          $score >= 60 ? 'D: Pass' :
          ( $score < 60 ? 'F: Fail – below passing mark' :
            '??' ) ) ) );

print "$result\n";

note:
Operator precedence – The ternary operators (? and :) bind loosely, so you often need parentheses when mixing them with other operators. example: $result = $a > $b ? $a : ($c < $d ? $c : $d);

advanced theoretical use:

Chaining (nesting) ternary operators

Because a ternary expression itself returns a value, you can place another ternary where either the true or false part belongs:

cond1 ? expr1
      : cond2 ? expr2
               : cond3 ? expr3
                        : expr4;
3 points · 0 comments · view on lemmy.world

0 Comments

No comments yet.