0

What is the meaning of the following statement in Perl:

num //= 0 
Osama Abdulsattar
  • 576
  • 1
  • 4
  • 11

3 Answers3

5

perldoc perlop lists the Perl operators.

Logical Defined-Or

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.

//= is just the assignment version of it.

Assignment operators work as in C. That is,

$x += 2;

is equivalent to

$x = $x + 2;

So it assigns 0 to num unless num is already defined.

This is distinct from || since there are defined values which aren't true (such as 0 or an empty string).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

$num = $num // 0;

is now the convenient way of

$num =defined$num ? $num : 0;

// is referred to as defined-or operator that instead of testing for truth, tests for defined-ness.

Unless variable is undef or array empty () (which actually evaluates to an undefined value in scalar context) — it's defined.

So my( $a, $b, $c ) = ( '', '0', 0 ) are all defined but false.

Beware prior to Perl 5.10 there was no such assignment like $pi //= PI.

Community
  • 1
  • 1
Pavel
  • 81
  • 1
  • 7
0

num //= 0, which is equivalent to

num = num // 0;

It means that it checks if the left operand is defined or not, if defined it returns the left operand else the right operand.

my $num;

$num //= 0;

print $num; # optputs 0

$num = 9;

$num //= 0;

print $num; # outputs 9
Pradeep
  • 3,093
  • 17
  • 21