Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie If..Else Question - why return true?

Status
Not open for further replies.

toddmanqa

Technical User
Aug 11, 2008
5
US
Here is my code:

#!/usr/bin/perl

$x = 2;

if ($x = 11) {
print "$x equals 11!";
} else {
print "$x does not equal 11!";
}

Why does it return, '11 equals 11'?
 
Hey - one I'm qualified to answer: Use '==' in your compare. Using if ($x = 11) is effectively assigning the value 11 to $x and then telling you about it with your print.
 
To potentially more fully answer your question, if I'm not mistaken, perl will do the following:
Code:
if [i]EXPR[/i] {
   # This will be executed if [i]EXPR[/i] evaluates to
   # anything [u]but[/u]:
   #    0
   #    "" -- i.e. defined with no value
   #    undef
}
Note that ($x = 11) evaluates to 11 - which is interpreted as true.
 
As pointed out, you have used "=": if($x = 11) when you should have used "==": if($x == 11) . A very common mistake.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top