Je Rog
Je Rog

Reputation: 5993

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?

Upvotes: 7

Views: 365

Answers (5)

Felix Kling
Felix Kling

Reputation: 816334

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.

Upvotes: 9

Dallaylaen
Dallaylaen

Reputation: 5308

For Perl, fig. 2: and has a very low priority in perl, it's not a synonym of &&'s. Therefore the sample is executed as (($a = 5) and ($b = 1)) which sets $a and $b to 5 and 1 respectively and returns a value of the last argument (i.e. 1).

After ++'s you get 6-2.

Upvotes: 2

RiaD
RiaD

Reputation: 47619

First example

$a = 2;
$b = 3;
if($b=1 && $a=5)  // means $b = (1 && $a=5)
{
   var_dump($b); //bool(true) because of &&
   $a++;
   $b++; //bool(true)++ ==true, ok
}
echo $a.'-'.$b;

hope you will not use those codes in production)

I'm noob in perl but i can suggest a&&b returns a or b (last of them if all of them converted to bool), not boolean, then $b = (1 && $a=5) returns $b=5 (is 5)

Upvotes: 5

ennuikiller
ennuikiller

Reputation: 46965

here's the issue: 1 && 5 returns 5 in perl. you get the result you expect if you code the conditional as if(($b=1) && ($a=5))

Upvotes: 4

Prashant Singh
Prashant Singh

Reputation: 3793

refer to http://sillythingsthatmatter.in/PHP/operators.php for good examples

Upvotes: 0

Related Questions