Tuesday, June 21, 2011

Comparison in perl

Perl has two different set of comparison operators for both numbers and string.

For string we need to use only the following operators
In case of string the comparison takes place ASCIIbetically -that is by comparing ASCII values of the characters in Strings.

'a' lt 'b'         TRUE
'a' eq 'A'      FALSE-capitalization
"joseph" eq "joseph "  FALSE-spaces count
"H"  cmp "He"  -1--cmp operator

The cmp operator does a string comparison and returns -1,0,1 depending on the left argument is greater than,less than the right argument.
This operator should not be used for string comparison

"aaaaaaaa"  == "fgdfgdfgdf"    TRUE always as for equal to operator the string always looks to be 0

Numeric comparison use the following:

0<5                     TRUE
10 == 10.0          TRUE
10 <=> 9.5          1     --->spaceship operator
The spaceship operator is like cmp for strings except it compares numerically.
Should not use string comparators for numeric.

'10' gt '2'               FALSE -  '1' sorts before 2
"10.0" eq "10"       FALSE-different strings

No comments:

Post a Comment