basics intermediate
How to use the defined-or operator in Perl
Question
How does the // (defined-or) operator work in Perl 5.10+?
The // operator returns its left operand if it's defined, otherwise returns the right operand. This is different from || which checks for truth:
use v5.10;
use strict;
use warnings;
my $value = 0;
my $undef;
# Using || (checks for truth)
my $result1 = $value || "default"; # Returns "default" (0 is false)
# Using // (checks for definedness)
my $result2 = $value // "default"; # Returns 0 (0 is defined)
my $result3 = $undef // "default"; # Returns "default" (undef not defined)
say "result1: $result1"; # default
say "result2: $result2"; # 0
say "result3: $result3"; # default
Use // when you want to distinguish between false values (0, empty string) and undefined values.