Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '//' mean in Perl? [duplicate]

I was searching in a lot of Perl books but I can't find an answer. I have this code, what I suppose it does is assign param's ticket to $ticket iff it exists if not, assign 0.

my $ticket   = $params->{ticket} // 0;
like image 401
gabolop Avatar asked Dec 12 '22 16:12

gabolop


2 Answers

// means defined-or. $ticket is assigned $params->{ticket} if it is defined, 0 otherwise.

Although it has no direct equivalent in C, Perl's // operator is related to its C-style or. In fact, it's exactly the same as ||, except that it tests the left hand side's definedness instead of its truth. Thus, EXPR1 // EXPR2 returns the value of EXPR1 if it's defined, otherwise, the value of EXPR2 is returned.

It was added in 5.10.

In the code above, $params->{ticket} can still have garbage in it, so make sure the value conforms to the expected pattern before using it.

like image 160
Sinan Ünür Avatar answered Jan 03 '23 23:01

Sinan Ünür


Perl documentation says:

"EXPR1 // EXPR2 returns the value of EXPR1 if it's defined, otherwise, the value of EXPR2 is returned."

It's similar to a logic or, but testing definedness.

like image 35
Rob I Avatar answered Jan 04 '23 01:01

Rob I