Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two objects in Perl without coercing them to the same type?

Tags:

perl

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.

like image 408
Pavel Avatar asked Dec 11 '22 08:12

Pavel


2 Answers

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.


  1. That's why it's still flagged as experimental.
like image 173
ikegami Avatar answered Jan 16 '23 15:01

ikegami


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);
like image 45
mob Avatar answered Jan 16 '23 15:01

mob