gpt4 book ai didi

perl - 为什么 '|' 没有被重载?

转载 作者:行者123 更新时间:2023-12-02 11:24:18 24 4
gpt4 key购买 nike

以下代码无法按预期工作。我错过了什么?

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

print( 5 | 5 ); # Prints '5' instead of '2.5'

最佳答案

overload仅适用于受祝福的引用(“对象”)。

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

关于perl - 为什么 '|' 没有被重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23890713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com