我读过这篇关于 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 whereasrequire
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 被要求执行一个文件(因为它被传递给
perl
、 require
、 do EXPR
或 eval EXPR
),它首先编译整个文件,然后执行刚刚编译的代码。如果有
use
或 BEGIN
在编译阶段遇到,那么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/