Perl DISCUSSION

Why is my Perl string comparison with == true for every value, and when should I use eq?

Started by aldianfaizun Perl eq vs ==string comparisonnumeric comparisonsort numericallyuse warnings
4 replies 248 views 5 participants
Latest activity · 30 Sep 2026

Why is my Perl string comparison with == true for every value, and when should I use eq?

aldianfaizun Perl Forum
#1

My script reads a command from a serial log and branches on it with if ($cmd == "start") { ... } elsif ($cmd == "stop") { ... }. The first branch runs for every command, including stop and reset. In another place, sort @readings puts 100 before 25 and 9 last.

I assume both problems are related to how Perl compares values. What is the rule?

Community replies 4

Re: Why is my Perl string comparison with == true for every value, and when should I use eq?

#2

Perl does not pick the comparison from the data; you pick it with the operator. ==, !=, <, >, <=, >= and <=> compare numbers. eq, ne, lt, gt, le, ge and cmp compare strings.

With == both sides are converted to numbers first. A string that does not start with a number converts to 0, so "stop" == "start" is 0 == 0, which is true. Write $cmd eq "start".

Re: Why is my Perl string comparison with == true for every value, and when should I use eq?

#3

Turn on use strict; use warnings; at the top of every script. With warnings enabled, the original line reports Argument "stop" isn't numeric in numeric eq (==), which points straight at the bug.

The conversion uses the leading numeric part of the string: "12abc" becomes 12 (with a warning), "3.0" becomes 3 and "1e3" becomes 1000. That is why "3.0" == 3 is true while "3.0" eq "3" is false. A hexadecimal string is not recognised: "0x1A" converts to 0, and you need hex("0x1A") to get 26.

Re: Why is my Perl string comparison with == true for every value, and when should I use eq?

#4

The sort problem is the same issue from the other side. sort @readings with no block compares as strings, character by character, so for 9, 25 and 100 the order is 100, 25, 9 because "1" sorts before "2" and "2" before "9". Give it a numeric comparison: sort { $a <=> $b } @readings returns 9, 25, 100, and sort { $b <=> $a } @readings gives descending order. For strings, sort { lc($a) cmp lc($b) } @names sorts without regard to case.

Re: Why is my Perl string comparison with == true for every value, and when should I use eq?

#5

One more thing to check when a string comparison that looks right still fails: input read with <STDIN> or from a file keeps its line ending. "start\n" eq "start" is false, so call chomp($cmd); first, and if the log comes from a Windows or serial source strip the carriage return as well with $cmd =~ s/\r?\n\z//;.

For floating-point values neither operator is a good equality test: 0.1 + 0.2 == 0.3 is false because of binary rounding. Compare against a tolerance, for example abs($x - $y) < 1e-9.

TEP COMMUNITY