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

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?

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;

As Adam says, Perl 5.10 has the // operator that tests its lefthand operator for defined-ness instead of truth:

 use 5.010;

 my $value = $this // $that;

If you are using an earlier version of Perl, it's a bit messy. The || won't work:

 my $value = $this || $that;

In that case, if $this is 0 or the empty string, both of which are defined, you'll get $that. To get around that, the idiom is to use the conditional operator so you can make your own check:

 my $value = defined( $this ) ? $this : $that;

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;

The question implied any number of arguments, so the answer implies a subroutine :

Here you get it - will return the first defined/non empty-string value of a list :

sub coalesce { (grep {length} @_)[0] }

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.


Need Your Help

return an empty vector c++

c++ object vector return

The requirement is that I need to search a vector to see if it contains the value passed in as the parameter. If the value exists in the vector, I return the vector. Else, I return an empty vector....

Ctrl+Enter jQuery in TEXTAREA

javascript jquery html hotkeys

How do I trigger something when the cursor is within TEXTAREA and Ctrl+Enter is pressed? Using jQuery. Thanks