In Perl, I know of three ways to test objects for equality: ==
, eq
, and ~~
. All of these tell me that 1
is equal to "1"
in Perl 5.
However, 1
and "1"
are not the same thing. How can I compare two objects so that 1
equals 1
, "1"
equals "1"
, 1
does not equal "1"
or 2
, and "1"
does not equal "01"
? Answers for both Perls would be appreciated.
Don't. In Perl, one is one. Polymorphism based on a value's type is bound to fail. That's why Perl has two comparison operators, and that's why ~~
is broken[1].
For example, the scalar returned by !0
contains three values, one stored as an integer, one stored as a floating point number, and one stored as a string.
For example, an object of class package Foo; use overload '0+' => sub { 1 }, fallback => 1;
might not contain one at all, but it's considered to be one in numerical and string contexts.
Serializers like Data::Dumper::Dumper
and JSON::encode_json
can treat scalars internally stored as numbers differently from scalars internally stored as strings, so you can compare serialized output:
use Data::Dumper;
$x = 1;
$y = "1";
$same = Dumper($x) eq Dumper($y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With