How to compare two objects in Perl without forcing them to the same type?

In Perl, I know three ways to test objects for equality: ==, eqand ~~. All this tells me what 1is equal "1"in Perl 5 .

However, 1and "1"- it's not the same thing. How to compare two objects so that 1equal 1, "1"equal "1", 1not equal to "1"or 2, but "1"not equal "01"? The answers for both Perls will be appreciated.

+4
source share
3 answers

not to do. In Perl, one is one. Value type polymorphism necessarily fails. This is why Perl has two comparison operators and why it is ~~broken [1] .

For example, the scalar returned !0contains three values, one of which is stored as an integer, one is stored as a floating-point number, and one is stored as a string.

For example, a class object package Foo; use overload '0+' => sub { 1 }, fallback => 1;may not contain it at all, but it is considered that it is one of the numeric and string contexts.


  • This is why it is still labeled experimental.
+11
source

, Data::Dumper::Dumper JSON::encode_json, , - , , , :

use Data::Dumper;
$x = 1;
$y = "1";
$same = Dumper($x) eq Dumper($y);
+1

This snippet can be used as a starting point for your comparison function:

my $num = 42;
my $str = "42";
say B::svref_2object(\$num)->FLAGS;
say B::svref_2object(\$str)->FLAGS;

You will see that the flags of both variables are different. Read perldoc Bfor more details.

You can also find the source code JSON::PP. Search for "sub value_to_json".

+1
source

Source: https://habr.com/ru/post/1693535/


All Articles