user1779868
user1779868

Reputation: 101

Strings matching

i wrote a code:

my $str = 'http://www.ykt.ru/cgi-bin/go?http://ya.ru';
my $str2 = 'http://ya.ru';
if ($str == $str2)
{
    print "str = str2";
}
else 
{
    print "str != str2";
}

and it shows me that str = str2. But it's false. Only if $str = 'http://ya.ru'; It will be true. Whats wrong?

Upvotes: 3

Views: 148

Answers (1)

raina77ow
raina77ow

Reputation: 106385

You should compare strings with eq operator, like this:

if ($str eq $str2) { ... }

It's actually quite a handy mnemonic rule: letters for strings, non-letters - for numbers (as each symbolic comparison operator has a 'wordy' alternative):

numbers | strings
----------------- 
  ==    |   eq
  !=    |   ne
  <     |   lt
  >     |   gt
  <=    |   le
  >=    |   ge
 <=>    |  cmp    

Otherwise a numeric comparison will be used: both operands will be cast to numbers, and the results of this cast will be compared. As both strings begin from non-numeric symbol (even after trimming), it effectively becomes (0 == 0).

Note that you actually would have this answer laid before you if you had begun your script with...

use warnings;

... pragma, like I've done here:

Argument "http://ya.ru" isn't numeric in numeric eq (==) at t.pl line 5. 
Argument "http://www.ykt.ru/cgi-bin/go?http://ya.ru" isn't numeric in numeric eq (==) at t.pl line 5.

Upvotes: 10

Related Questions