perl - 与 perl 内置函数同名的包方法

标签 perl

所以我的模块有一个名为 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/

相关文章:

python - 按多列对数据进行排序

perl - 将数据重定向到文件时出错

c++ - 如何将多维映射从 c++ 转换为 perl 中的哈希

windows - 如何使用批处理文件在 Windows 下为 Perl 程序创建快捷方式?

regex - Perl 警告 : Use of uninitialized value in concatenation (. ) 或字符串

perl - 如何使用 perl Archive::Zip 将文件添加到存档?

algorithm - sed优化(基于较小数据集的大文件修改)

perl - Vim 像 Perl IDE

java - 将从 URL 输出的 JSON 保存到文件

regex - perl - 使用正则表达式获取子字符串