所以我的模块有一个名为 push
的方法。在这个方法中,我调用了 perl 的内置 push
函数。现在我有另一个名为 unshift
的方法,在这个方法中,我再次调用 perl 的内置 push
函数。
1 package Deque;
2
3 ...
4 sub push {
5 my ($self, $node) = @_;
6 push @{ $self->{nodes} } => $node;
7 ...
8 }
9
10 sub unshift {
11 my ($self, $node) = @_;
12 push @{ $self->{nodes} } => $node;
13 ...
14 }
程序运行,但我收到此警告 Ambiguous call resolved as CORE::push() ... line 12
。
所以我将第 12 行更改为 CORE::push @{ $self->{nodes} } => $node
,警告消失了。
为什么 perl 没有警告我第 6 行? 有没有更好的方法来摆脱警告?我无法更改方法名称。
最佳答案
请注意,如果交换子例程,则根本不会显示任何警告:
sub unshift {
my ($self, $node) = @_;
push @{ $self->{nodes} } => $node;
}
sub push {
my ($self, $node) = @_;
push @{ $self->{nodes} } => $node;
}
...但是如果预先声明了 push
,则有两个:
sub push;
sub unshift {
my ($self, $node) = @_;
push @{ $self->{nodes} } => $node;
}
sub push {
my ($self, $node) = @_;
push @{ $self->{nodes} } => $node;
}
# Ambiguous call resolved as CORE::push(), qualify as such or use & at line 10.
# Ambiguous call resolved as CORE::push(), qualify as such or use & at line 15.
我的猜测是,包中定义的 push
名称在整个子例程的主体被解析之前基本上不会被考虑在内。这就是为什么在子例程中此调用不被视为不明确的原因。
不过,我宁愿在所有相应的调用前加上 CORE::
前缀,如 perldiag 中所建议的那样.
To silently interpret [the subroutine name] as the Perl operator, use the
CORE::
prefix on the operator (e.g.CORE::log($x)
) or declare the subroutine to be an object method.
关于perl - 与 perl 内置函数同名的包方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22804438/