The following code does not work as expected. What am I missing?
use strict;
use warnings;
use overload '|' => sub { 1 / ( 1 / $_[0] + 1 / $_[1] ) };
print( 5 | 5 ); # Prints '5' instead of '2.5'
overload
works only on blessed references ("objects").
package MyNumber;
use strict;
use warnings;
use overload '|' => sub { 1 / ( 1 / +$_[0] + 1 / +$_[1] ) },
'0+' => sub { $_[0]->{value} }, # Cast to number
fallback => 1; # Allow fallback conversions
# "Constructor", bless number as MyNumber
sub num {
my $self = { value => $_[0] }; # can be any reference
return bless $self, "MyNumber";
}
print(num(5) | num(5));
my $a = num(5);
print ($a | 5); # This works too
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