Why not '|' overloaded?

The following code does not work properly. 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'
+4
source share
3 answers

overload only works on blissful links ("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
+9
source

Overloading works on objects, for example:

use v5.10;

package Number {
    use overload 
        '|' => sub { 1 / ( 1 / ${$_[0]} + 1 / ${$_[1]} ) },
        fallback => 1
        ;

    sub new {
        my( $class, $arg ) = @_;
        bless \ $arg, $class;
        }
    }   

my $n = Number->new( 5 );
my $m = Number->new( 5 );


say( $n | $m );

There are many things to watch out for since, since Perl 5 does not send multiple methods. In your routine, you need to figure out the second argument, and so right. This can get complicated. I would prefer to use the usual methods for this.

+5
source

[ . , .]

autoboxing:

use strict;
use warnings;

use overload '|' => sub { 1 / ( 1 / ${$_[0]} + 1 / ${$_[1]} ) };

BEGIN { overload::constant integer => sub { my ($n) = @_; bless(\$n) }; }

print( 5 | 5, "\n" );  # 2.5
+4

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


All Articles