RetroFed Forum
Your home away from modern life.
Chaining ternary operators (raising awareness / mini-lesson )
Post Reply
AuthorMessage
cm0002 suppo.fi cm0002@suppo.fi
Joined: 2025-11-10
Quote

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.

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.

  • finally, The final : supplies the fallback value, acting as the “else” case.

  • 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.

3   Original
okwhateverdude lemmy.world okwhateverdude@lemmy.world
Joined: 2023-08-01
#2 · Quote Reply

Ugh. No thanks. What a pain in the ass to read! Tell your clankers not to write code like that! Just because you can produce dense idioms in Perl doesn't mean you should.

1
Post Reply
Back to top