Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence issue in Perl and PHP

PHP:

$a = 2;
$b = 3;
if($b=1 && $a=5)
{
   $a++;
   $b++;
}
echo $a.'-'.$b;


$a = 2;
$b = 3;
if($a=5 and $b=1)
{
   $a++;
   $b++;
}
echo $a.'-'.$b;

Output 6-16-2.I don't understand the 1 here.

Perl :

$a = 2;
$b = 3;
if($b=1 && $a=5)
{
     $a++;                                                                            
     $b++;
}
print $a.'-'.$b;


$a = 2;
$b = 3;
if($a=5 and $b=1)
{
    $a++;
    $b++;
}
print $a.'-'.$b;

Output 6-66-2, I don't understand the second 6 here.

Anyone knows the reason?

Actually I know && has higher precedence than and,but I still has the doubt when knowing this before hand.

UPDATE

Now I understand the PHP one,what about the Perl one?

like image 442
Je Rog Avatar asked Aug 03 '11 13:08

Je Rog


1 Answers

Regarding Perl:

Unlike PHP (but like Python, JavaScript, etc.) the boolean operators don't return a boolean value but the value that made the expression true (or the last value) determines the final result of the expression (source).

$b=1 && $a=5

is evaluated as

$b = (1 && $a=5) // same as in PHP

which is the same as $b = (1 && 5) (assignment "returns" the assigned value) and assigns 5 to $b.


The bottom line is: The operator precedence is the same in Perl and PHP (at least in this case), but they differ in what value is returned by the boolean operators.

FWIW, PHP's operator precedence can be found here.


What's more interesting (at least this was new to me) is that PHP does not perform type conversion for the increment/decrement operators.

So if $b is true, then $b++ leaves the value as true, while e.g. $b += 1 assigns 2 to $b.


†: What I mean with this is that it returns the first (leftmost) value which

  • evaluates to false in case of &&
  • evaluates to true in case of ||

or the last value of the expression.

like image 180
Felix Kling Avatar answered Oct 21 '22 22:10

Felix Kling