Is there a Perl equivalent to the null coalescing operator (??) in C#?

Viewed 6821

I started to really like C#'s ?? operator. And I am quite used to the fact, that where there is something handy in some language, it's most probably in Perl too.

However, I cannot find ?? equivalent in Perl. Is there any?

5 Answers

As of 5.10 there is the // operator, which is semantically equivalent if you consider the concept of undef in Perl to be equivalent to the concept of null in C#.

Example A:

my $a = undef;
my $b = $a // 5;  # $b = 5;

Example B:

my $a = 0;
my $b = $a // 5;  # $b = 0;

Actually, the short-circuit OR operator will also work when evaluating undef:

my $b = undef || 5;  # $b = 5;

However, it will fail when evaluating 0 but true:

my $b = 0 || 5;  # $b = 5;

Not that I know of.

Perl isn't really a big user of the null concept. It does have a test for whether a variable is undefined. No special operator like the ?? though, but you can use the conditional ?: operator with an undef test and get pretty close.

And I don't see anything in the perl operator list either.

Related