Equality Operator Warnings

Has something changed in Perl, or has it always been that examples like the second ( $number eq 'a') don't throw a warning?

#!/usr/bin/env perl
use warnings;
use 5.12.0;

my $string = 'l';
if ($string == 0) {};

my $number = 1;
if ($number eq 'a') {};


# Argument "l" isn't numeric in numeric eq (==) at ./perl.pl line 6.
+3
source share
3 answers

Perl will try to convert the scalar to the type required by the context in which it is used.

There is a valid conversion from any scalar type to a string, so this is always done silently.

Converting to a number is also performed silently if the string passes the test looks_like_number(available through Scalar::Util). Otherwise, a warning is issued, and in any case, the “best guess” approximation is performed.

my $string = '9';
if ( $string == 9 ) { print "YES" };

9, YES .

my $string = '9,8';
if ( $string == 9 ) { print "YES" };

Argument "9,8" isn't numeric in numeric eq (==), 9, YES .

, , , 5.0.

+6

.

if, l . l . .

if 1 . 1 '1' , , .

+4

"L"? "L" "". , .

>perl -wE"say '1' == 0;"


>perl -wE"say 1 eq 'a';"


>

,

  • , Perl .
  • If a string is needed, Perl converts the number to a string without warning.

Very consistent.

You get a warning when you try to convert the lowercase L to a number, but how surprising is that?

0
source

All Articles