sid_com sid_com - 5 months ago 20
Perl Question

Warnings on equality operators

Has something changed in Perl or has it always been this way, 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.

Answer

Perl will be try to convert a scalar to the type required by the context where it is used.

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

Conversion to a number is also done silently if the string passes a looks_like_number test (accessible through Scalar::Util). Otherwise a warning is raised and a 'best guess' approximation is done anyway.

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

Converts the string silently to integer 9, the test succeeds and YES is printed.

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

Raises the warning Argument "9,8" isn't numeric in numeric eq (==), converts the string to integer 9, the test succeeds and YES is printed.

To my knowledge it has always been this way, at least since v5.0.

Comments