The ternary operator chooses one expression, and // supplies a default for undef.

ternary A ternary expression uses `condition ? true_value : false_value`.

Ternary and Defaulting

count
ternary_default.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $count = 0;
my $label = $count == 1 ? "item" : "items";
my $owner = undef;
my $display_owner = $owner // "unassigned";

print "count=$count\n";
print "label=$label\n";
print "owner=$display_owner\n";
use strict;
use warnings;

my $count = 1;
my $label = $count == 1 ? "item" : "items";
my $owner = undef;
my $display_owner = $owner // "unassigned";

print "count=$count\n";
print "label=$label\n";
print "owner=$display_owner\n";
use strict;
use warnings;

my $count = 5;
my $label = $count == 1 ? "item" : "items";
my $owner = undef;
my $display_owner = $owner // "unassigned";

print "count=$count\n";
print "label=$label\n";
print "owner=$display_owner\n";
  1. $count ← 0, $label ← items, $owner ← (empty), $display_owner ← unassigned

    4my $count→ 0 = 0; #@count=1, 55my $label→ items = $count0 == 1 ? "item" : "items";6my $owner→ (empty) = undef;7my $display_owner→ unassigned = $owner(empty) // "unassigned";89print "count=$count0\n";10print "label=$labelitems\n";11print "owner=$display_ownerunassigned\n";
    outputcount=0
    label=items
    owner=unassigned
  1. $count ← 1, $label ← item, $owner ← (empty), $display_owner ← unassigned

    4my $count→ 1 = 1;5my $label→ item = $count1 == 1 ? "item" : "items";6my $owner→ (empty) = undef;7my $display_owner→ unassigned = $owner(empty) // "unassigned";89print "count=$count1\n";10print "label=$labelitem\n";11print "owner=$display_ownerunassigned\n";
    outputcount=1
    label=item
    owner=unassigned
  1. $count ← 5, $label ← items, $owner ← (empty), $display_owner ← unassigned

    4my $count→ 5 = 5;5my $label→ items = $count5 == 1 ? "item" : "items";6my $owner→ (empty) = undef;7my $display_owner→ unassigned = $owner(empty) // "unassigned";89print "count=$count5\n";10print "label=$labelitems\n";11print "owner=$display_ownerunassigned\n";
    outputcount=5
    label=items
    owner=unassigned

Choose Label and Owner

  1. $count starts at 0.
  2. The ternary checks whether $count == 1.
  3. Because the check is false, $label becomes items.
  4. $owner is undef, so // chooses unassigned. | Count | Label | | --- | --- | | 0 | items | | 1 | item | | 5 | items |

Exercise: ternary_default.pl

Use a ternary for item/items and // to show unassigned for an undefined owner