子例程签名是否适用于 overload.pm?

Do subroutine signatures work with overload.pm?

有了流畅的代码..

use experimental 'signatures';

package O {
    use overload
        q[""]  => \&as_str
    ;
    sub as_str ($self) { "Hello World!" }
    sub new ($class) {
        bless {}, $class
    }
};

my $o = O->new;
print "$o";

我会得到,

Too many arguments for subroutine 'O::as_str'

如何同时使用 (a) 签名和 (b) 重载。

来自 overload.pm

上的文档

Three arguments are passed to all subroutines specified in the use overload directive (with exceptions - see below, particularly "nomethod").

  1. The first of these is the operand providing the overloaded operator implementation - in this case, the object whose minus() method is being called.

  2. The second argument is the other operand, or undef in the case of a unary operator.

  3. The third argument is set to TRUE if (and only if) the two operands have been swapped. Perl may do this to ensure that the first argument ($self) is an object implementing the overloaded operation, in line with general object calling conventions.

基本上,overload 支持二元运算符,它调用的所有 subs 都被原型化为接受三个参数。所以考虑到这一点,你会想要

sub as_str ($lhs, $rhs, $is_swapped) { "Hello World!" }

或者你可以告诉它 ignore the other arguments using the $

sub as_str ($lhs, $, $) { "Hello World!" }