gpt4 book ai didi

perl - 当 sub Foo::bar {} 和 sub bar {} 都属于包 Foo 时,它们有什么区别?

转载 作者:行者123 更新时间:2023-12-04 07:37:45 25 4
gpt4 key购买 nike

假设我们有这样的代码

package Foo;
sub bar {
say 'hi';
}

和这个
package Foo;
sub Foo::bar {
say 'hi';
}

我认为它们是等价的,所以我们可以这样做
Foo->bar();

我们是否使用完全限定名称定义方法。但是,在某些情况下,它们确实是不同的。例如,在 perldoc -f require 给出的例子中,方法 INC必须使用包名称完全限定:
# In Foo.pm
package Foo;
sub new { ... }
sub Foo::INC {
my ($self, $filename) = @_;
...
}
# In the main program
push @INC, Foo->new(...);

如果我们没有完全限定方法名称,则会发生编译时错误。那么,全限定名和没有包名的区别是什么?

最佳答案

引起@main::INC的机制可作为 @INC 全局访问也会引起 sub INC { }意思是 sub main::INC { } .
报价 perlvar ,

Perl identifiers that begin with digits, control characters, or punctuation characters are exempt from the effects of the package declaration and are always forced to be in package main; they are also exempt from strict 'vars' errors. A few other names are also exempt in these ways:

ENV STDIN
INC STDOUT
ARGV STDERR
ARGVOUT
SIG


If we don't fully qualify the method name, then a compile-time error occurs.


嗯......它不会做你想要的,但它也不会导致编译时错误。
$ perl -ce'
package Foo;
sub new { ... }
sub INC {
my ($self, $filename) = @_;
...
}

push @INC, Foo->new("...");
'
-e syntax OK

关于perl - 当 sub Foo::bar {} 和 sub bar {} 都属于包 Foo 时,它们有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24883095/

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