You only overloaded stringification, not string comparison. The overload
pragma will however use the overloaded stringification for the string comparison if you specify the fallback => 1
parameter:
my $test = MyTest->new('test');
print 'yes' if $test eq 'test';
package MyTest;
use overload
fallback => 1,
'""' => sub { my $self = shift; return $self->{'str'} };
sub new {
my ( $class, $str ) = @_;
return bless { str => $str }, $class;
}
Details on why this works:
When handed an overloaded object, the eq
operator will try to invoke the eq
overload. We did not provide an overload, and we didn't provide a cmp
overload from which eq
could be autogenerated. Therefore, Perl will issue that error.
With fallback => 1
enabled, the error is suppressed and Perl will do what it would do anyway – coerce the arguments to strings (which invokes stringification overloading or other magic), and compare them.