views:

209

answers:

4

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?

A: 

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.

whatsisname
well, you didn't answer me, but thanks to the page I realised my question was a little bit off and I can just use simple || (I put it as a separate answer)
Karel Bílek
no. I am actually wrong
Karel Bílek
+15  A: 

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.

Adam Bellaire
yes, I automatically thought of undef as equivalent of NULLthanks
Karel Bílek
The pre-5.10 idiom is just `defined($a) ? $a : $b`, which does the job and reads clearly enough.
hobbs
hobbs: yeah, but I would have to write it 2 times (which is not the same, when it's, for example, a call to subroutine)
Karel Bílek
btw, I really like that my premise "when the feature is nice, it's probably in perl too" still holds :)
Karel Bílek
+2  A: 

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;
Pedro Silva
A: 

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;
brian d foy