首页 > 解决方案 > 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 的情况下有效吗?

标签: pythonperl

解决方案


Perl 使用多阶段编译模型。子例程是在实际运行时间之前的早期阶段定义的,因此不需要前向声明。

相比之下,Python 在运行时执行函数定义。保存函数的变量必须先赋值(由 隐式def),然后才能作为函数调用。

如果我们将这些运行时语义转换回 Perl,代码将如下所示:

# at runtime:
$test->();

my $test = \&test;

# at compile time:
sub test { print 'here' }

请注意,$test变量是在声明和分配之前访问的。


推荐阅读