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?
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?
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.
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;
EDIT: I note that the code syntax highlighter hates this operator.
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;
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;