Perl字符串和< &安培; >运营商

时间:2011-11-16 15:16:57

标签: perl operators string-comparison

为了比较字符串,通常使用lt,gt等..

当我使用数字运算符比较字符串时perl究竟做了什么? (<,>)

my $str1 = 'Joe';
my $str2 = 'flight';

我想在执行$str1 gt $str2 perl时比较ASCII码(?),但是当我执行以下操作时会发生什么:

$str1 > $str2

感谢

3 个答案:

答案 0 :(得分:4)

首先你得到一个警告:

Argument "flight" isn't numeric in numeric lt (<) at 
Argument "Joe" isn't numeric in numeric lt (<) at

然后perl将这些字符串转换为整数,使它们变为0,然后进行比较。

答案 1 :(得分:1)

对Perl来说,10是10,它是存储为字符串(PV),有符号整数(IV),无符号整数(UV)还是浮点数(NV)。

<>==比较其操作数的数值。那么非数字的东西的数值为零*,因此flight的数值为零(带警告),Joe的数值为零(带警告),所以他们是平等的。

另一方面,字符串10的数值为10,字符串2的数值为2,所以

10 >= 2       # True
'10' >= '2'   # True

10 ge 2       # False (ord('1') is less than ord('2'))
'10' ge '2'   # False

* - 对象可以覆盖它,引用的数值是引用值的地址。

答案 2 :(得分:0)

what exactly perl does when I compare strings using numerical operators? (<, >)

perl在比较之前将字符串转换为数字。

两个示例字符串都转换为零。

but what happens when I do the following:
$str1 > $str2

根据“整理顺序”(名义字母顺序)比较它们, 好像字符串按照电话簿中的顺序排序。

'barney' < 'bammbam'

是假的:

compare 1st letters - tied
compare 2nd letters - tied
compare 3rd letters - "m" comes before "r", so the comparison is false.