Perl 数字与字符串运算符之区别
发布时间:2020-12-16 00:30:11 所属栏目:大数据 来源:网络整理
导读:在Perl中,字符串比较和数字比较是由不同的运算符来完成的: 数字比较运算符: ,,=,=,==,!= 字符串比较运算符: lt,gt,le,ge,eq,ne cmp: 比较字符串,返回 -1,0 或者 1。 =: 比较数字,返回 -1,0 或者 1。 =~:用正则表达式来匹配,匹配的话返回True。 !~
在Perl中,字符串比较和数字比较是由不同的运算符来完成的:
我有好几次都用错了,结果浪费了很多时间在调试上面。 #!/usr/bin/env perl use strict; use warnings; my $num1 = 1; my $num2 = 1.0; my $two_numbers = "$num1 and $num2"; my $str1 = "1abc"; my $str2 = "1xyz"; my $two_strings = "$str1 and $str2"; print "Compare two numbers using !=n"; if ($num1 != $num2) { print "$two_numbers are not equaln"; } else { print "$two_numbers are equaln"; } print "Compare two strings using !=: get wrong resultn"; if ($str1 != $str2) { print "$two_strings are not equaln"; } else { print "$two_strings are equaln"; } print "Compare two numbers using nen"; if ($num1 ne $num2) { print "$two_numbers are not equaln"; } else { print "$two_numbers are equaln"; } print "Compare two strings using nen"; if ($str1 ne $str2) { print "$two_strings are not equaln"; } else { print "$two_strings are equaln"; } Compare two numbers using != 1 and 1 are equal Compare two strings using !=: get wrong result Argument "1xyz" isn't numeric in numeric ne (!=) at compare_operators.pl line 23. Argument "1abc" isn't numeric in numeric ne (!=) at compare_operators.pl line 23. 1abc and 1xyz are equal Compare two numbers using ne 1 and 1 are equal Compare two strings using ne 1abc and 1xyz are not equal (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |