Why do these 2 pieces of code yield different outputs?
$a = 3;
($a == 4) and print "But I wanted apple, cherry, or blueberry!\n" ;
gives No program output but
$a = 3;
print "But I wanted apple, cherry, or blueberry!\n" and ($a == 4);
gives: But I wanted apple, cherry, or blueberry!
Because
andis a so-called “short circuit” operator. Meaning that if you havecondition1 and condition2, then the first condition is evaluated, and only if the first condition returns true is the second condition evaluated.So, in
the condition
$a==4is false and so theprintstatement isn’t evaluated.However, in
The
printstatement does its thing and returnstrue. The second condition is evaluated (which is obviouslyfalse), but the printing is already done.