perl - Perl 脚本中的 'at compile-time' 是什么意思?

标签 perl runtime compile-time

我读过这篇关于 Perl 的文章:

Perl is an interpreted language and doesn't compile.


我也看到了 at compile-time 的讨论和 at run-time .
特别是当我寻找 use 的使用时和 require ,它显示了一个区别:

use normally loads the module at compile time whereas require does at run time.


Perl 真的会编译脚本吗? Perl 脚本中的“编译时”是什么意思?

最佳答案

Perl 代码在执行之前被编译,而不是机器代码。有点像Java编译成字节码的方式,但结果是更高层次的。

# B::Concise shows the opcode tree that results from compiling Perl code

$ perl -MO=Concise,-exec -e'print("Hello, world!\n") for 1..3;'
1  <0> enter
2  <;> nextstate(main 1 -e:1) v:{
3  <0> pushmark s
4  <$> const[IV 1] s
5  <$> const[IV 3] s
6  <#> gv[*_] s
7  <{> enteriter(next->b last->e redo->8) lKS/8
c  <0> iter s
d  <|> and(other->8) vK/1
8      <0> pushmark s
9      <$> const[PV "Hello, world!\n"] s
a      <@> print vK
b      <0> unstack v
           goto c
e  <2> leaveloop vK/2
f  <@> leave[1 ref] vKP/REFC
-e syntax OK

当 Perl 被要求执行一个文件(因为它被传递给 perlrequiredo EXPReval EXPR ),它首先编译整个文件,然后执行刚刚编译的代码。

如果有 useBEGIN在编译阶段遇到,那么use声明或 BEGIN块在编译完成后立即执行。
# -c causes the main program to be compiled but not executed.

$ perl -c -E'
   say "abc";
   BEGIN { say "def"; }
   say "ghi";
'
def
-e syntax OK

$ perl -E'
   say "abc";
   BEGIN { say "def"; }
   say "ghi";
'
def
abc
ghi

在编译时可以检测到某些错误。
$ perl -c -E'say "abc" "def";'
String found where operator expected at -e line 1, near ""abc" "def""
        (Missing operator before  "def"?)
syntax error at -e line 1, near ""abc" "def""
-e had compilation errors.

别人不能。
$ perl -c -E'$x={}; $x->[0]'
-e syntax OK

$ perl -E'$x={}; $x->[0]'
Not an ARRAY reference at -e line 1.

关于perl - Perl 脚本中的 'at compile-time' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29509087/

相关文章:

perl - 如何使用 VIM 修复 perl 语法错误 "missing right curly or square bracket"?

java - 启动过程的非法参数

ios - 如何列出 NSManagedObject 的变量

c++ - 如何在编译时检查类型是否为多态

function - D 编译时函数类型提取

haskell - 如何正确地将编译时信息传递给 Template Haskell 函数?

Perl 和 Selenium::远程::驱动程序

html - 如何使用 Perl 将文件转换为 HTML 表格?

linux - 从邮件头解析发件人原始IP的Perl脚本

Java 执行命令行并在询问时总是替换 [Y/N]