Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't '|' being overloaded?

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'
like image 203
Zaid Avatar asked May 27 '14 13:05

Zaid


1 Answers

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
like image 140
el.pescado - нет войне Avatar answered Oct 17 '22 08:10

el.pescado - нет войне