Reputation: 25117
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.
Upvotes: 3
Views: 114
Reputation: 385657
Did you use a lowercase "L" on purpose? It's often hard to tell the difference between a lowercase "L" and one. You would have answered your own question if you had used a one instead.
>perl -wE"say '1' == 0;"
>perl -wE"say 1 eq 'a';"
>
As you can see,
Very consistent.
You get a warning when you try to convert a lowercase L to a number, but how is that surprising?
Upvotes: 0
Reputation: 126722
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.
Upvotes: 6
Reputation: 74222
It has been that way.
In the first if
, l
is considered to be in numeric context. However, l
cannot be converted to a number. Therefore, a warning is emitted.
In the second if
, the number 1
is considered to be in string context. Therefore the number 1
is converted to the string '1'
before comparison and hence no warnings are emitted.
Upvotes: 4