PHA
PHA

Reputation: 1668

What do the // and || operators do in Perl?

Can someone explain me what does this if is checking and when it is passed?

if ( $rate_minimum || 0 ) > ( (4 * $rate_max_min) // 120  ):

sorry for not being a perl developer

Upvotes: 2

Views: 94

Answers (2)

Sobrique
Sobrique

Reputation: 53508

|| is the boolean or operator. It will return $rate_minimum if $rate_minimum is true, and 0 otherwise. The false values are primarily 0, '' and undef.

// is very similar, but only tests defined-ness. (And is only available since Perl 5.10). This means a value of 0 still counts, and so if $rate_max_min is zero, it won't get replaced with 120. (Where it would if || had been used)

So $rate_miniumum || 0 will return $rate_minumum unless it is either: 0, an empty string or undefined. In which case the || will kick in, and it'll be zero instead.

The second part tests if $rate_max_min is defined and if it isn't, replace that value with 120. (Which allows it to be zero)

See perlop for more detail.

As a related point - you can also do ||= and //= to conditionally assign.

E.g.

my $value = undef;
$value //= 42;
print $value,"\n";
# 42 

$value = 0; 
$value //= 42;
print $value,"\n";
# 0

$value = 0;
$value ||=  42;
print $value,"\n";
# 42

Edit: As noted by melpomene

As written, (4 * $rate_min_max) // 120 is useless because the result of * is never undef.

That conditional should probably be:

4 * ( $rate_min_max // 30 )

instead.

e.g.:

my $rate_min_max = 0;
print 4 * ( $rate_min_max // 30 ),"\n";
$rate_min_max = undef;
print 4 * ( $rate_min_max // 30 ),"\n";

Upvotes: 7

Amar Singh
Amar Singh

Reputation: 5622

Following explanation will help you :

See || is an OR logical operator and // is 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.

Upvotes: 1

Related Questions