开发者

Is there a generic way to do comparison both numeric and string in Perl?

As everyone knows, the numeric's comparison uses different operators to string's. So Is there a generic way to do compar开发者_Go百科ison both numeric and string in Perl ? Should I always check the value is numeric or string before doing the comparison? I am a freshman in Perl. Please help if you have some idea. Thanks.


In addition to ways already mentioned, when using perl > 5.10.1, smart matching can be used. Specifically look at lines 29 .. 32 in the referenced table. If one operand look like a number, numeric comparison is used, otherwise fallback to string.


Well, usually you know what kind of data a particular variable holds at a particular point in time. Can you explain more what case you are thinking of where you wouldn't?

There are modules tailored to things like complex version numbers that may have multiple string/numeric parts. Sort::Naturally is one.


You should use numeric comparison when you want to compare numbers and string comparison when you want to compare strings. That's really all there is to it. You're probably overthinking it.

If you really need to test for both string and numeric equality, just test for both:

if ( ( $foo eq $bar ) && ( $foo == $bar ) )


When in doubt, use eq. It works for numbers as well. You only need numeric operations when you want to count something.

Perl will convert numbers to strings and vice-versa when needed, however, not all strings can be represented by numbers, so you'll get a warning and a zero value (while we are at it: always use strict; and use warnings; ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜