这有效:
use strict;
X("xxxxxx");
sub X { print shift;}
这会产生一个错误:
use strict;
BEGIN {
X("xxxxxx");
}
sub X { print shift;}
Error:
Undefined subroutine &main::X called at ./test.pl line 5.
这是有道理的,因为执行 sub 时我们正处于编译阶段的中间......所以编译器还没有到达 sub 声明/定义。
... 但:添加前向声明(在 BEGIN 块之前或其中)没有帮助:
use strict;
sub X;
BEGIN {
X("xxxxxx");
}
sub X { print shift;}
为什么在 BEGIN 块中调用函数时前向声明不起作用?我假设它发生在编译阶段,方式my
声明确实如此。
perldoc perlsub
似乎没有任何亮点。
A BEGIN
block is executed as soon as it has been parsed. This means that perl has'nt seen the definition of the sub yet1. Your only solution is to define the function before it's used:
sub foo { print shift }
# When the parser reaches this point, the "foo" sub has been compiled
BEGIN {
# Ergo, "foo" can be used here
foo("xxx");
}
# The BEGIN block is executed once the parser arrives here
您还可以选择稍后执行的移相器,例如INIT
:
INIT {
foo("xxx");
}
sub foo { print shift }
BEGIN
和朋友记录在perldoc perlmod
- 像这样的预声明
sub foo;
仅在原型上下文中为解析器提供指导,以及裸字与子例程调用消歧。它不会使解析器跳转到实际定义。由预声明生成的子例程存根实际上不可调用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)