- Prison Code Breaker Diary -

=> aka: Nhật Kí Code Tù

Categories

I'm talking about the conditional statement IF.
Here is the definition:

IF (exp) {
   (statement)
}
Try this example:
$age = 23; 
if ( $age == 23 ) {
   print "I am 23 years-old", '\n'
}
Certainly perl evaluates the expression is TRUE since $age is assigned to the value '23'.
How about this case:
if ( $age = 23 ) {
   print "I am 23 years-old", '\n'
}
Still you've got the result printed. But how do you explain what perl does to this evaluation?

1. First, $age is assigned to value '23'.
2. The expression is evaluted whether it is TRUE or FALSE, which means, $age is ZERO or non-ZERO. So, it's TRUE right here because '23' is definitely not '0'.
3. Statement 'print' is called.

Rewrite the explanation into the code itself:
$age = 23;
if ($age) {
   print "I am 23 years-old", '\n'
} 

If u try with constants assignment, u'll get error
if ( 20 = 55 ) {    
    print "is it ok?", '\n'
}

Found = in conditional, should be ==
(W syntax) You said

if ($foo = 123)

when you meant

if ($foo == 123)

(or something like that).

Can't modify constant item in scalar assignment
A fatal error (trappable)
You aren't allowed to assign to the item indicated, or otherwise try
to change it, such as with an auto-increment.

Same results but different operators mean differences.

I'm mentioning about the '=' and the '==' operators with different means, applied to all logical cases.

0 comments

Post a Comment