python - Perl 和 Python 在预声明函数方面的区别
问题描述
Perl
test();
sub test {
print 'here';
}
输出
here
Python
test()
def test():
print('here')
return
输出
Traceback (most recent call last):
File "pythontest", line 2, in <module>
test()
NameError: name 'test' is not defined
我知道在 Python 中我们需要在调用它们之前定义函数,因此上面的代码不适用于 Python。
我认为它与 Perl 相同,但它有效!
有人可以解释为什么它在 Perl 的情况下有效吗?
解决方案
Perl 使用多阶段编译模型。子例程是在实际运行时间之前的早期阶段定义的,因此不需要前向声明。
相比之下,Python 在运行时执行函数定义。保存函数的变量必须先赋值(由 隐式def
),然后才能作为函数调用。
如果我们将这些运行时语义转换回 Perl,代码将如下所示:
# at runtime:
$test->();
my $test = \&test;
# at compile time:
sub test { print 'here' }
请注意,$test
变量是在声明和分配之前访问的。
推荐阅读
- amazon-web-services - ECS任务中线程号如何映射到CPU单元?
- arrays - 内爆函数在codeigniter中不起作用
- python - 从 sklearn.tree.export 导入 export_text 时出错
- c++ - 程序不终止
- image - 在 Flutter Web 中显示选定的图像
- javascript - 在引导模式内打印内容时未显示内容,但打印时出现空白页
- javascript - 如何在 nodejs 中使用 process.stdin 获取 Hackerearth 代码的用户输入
- c# - WindowsFormHost 不适用于 WPF 用户控件
- android - Firebase- 带有 Twitter 的 Sigin 显示您的浏览器不再受支持
- python - Python:如何在另一个指定字符串之后立即提取字符串