(根据/sf/answers/1223568601/它应该可以工作,但不能)我有一些这样的代码:
use strict;
use warnings;
if (open(my $fh, '>', '/tmp/test')) {
print $fh << 'TAG';
BEGIN {
something;
}
TAG
close($fh);
}
Run Code Online (Sandbox Code Playgroud)
如果我省略$fh
(这是一个为输出而打开的文件句柄,顺便说一句),该BEGIN
块将正确输出(到STDOUT
)。但是,当我添加时$fh
,Perl (5.18, 5.26) 尝试执行something
导致运行时错误:
Bareword "something" not allowed while "strict subs" in use at /tmp/heredoc2.pl line 6.
syntax error at /tmp/heredoc2.pl line 9, near "FOO
close"
Execution of /tmp/heredoc2.pl aborted due to compilation errors.
Run Code Online (Sandbox Code Playgroud)
怎么了?
问题的细节很有趣(原 Perl 是 5.18.2,但以 5.26.1 为例):
首先是一些不需要的代码$fh
:
#!/usr/bin/perl
use strict;
use warnings;
if (open(my $fh, '>', '/tmp/test')) {
print << 'FOO_BAR';
BEGIN {
something;
}
FOO_BAR
close($fh);
}
Run Code Online (Sandbox Code Playgroud)
perl -c
说 : /tmp/heredoc.pl syntax OK
,但没有任何输出!
如果我$fh
之前添加<<
,我会收到这个错误:
#!/usr/bin/perl
use strict;
use warnings;
if (open(my $fh, '>', '/tmp/test')) {
print << 'FOO_BAR';
BEGIN {
something;
}
FOO_BAR
close($fh);
}
Run Code Online (Sandbox Code Playgroud)
最后,如果我删除之前的空格'FOO_BAR'
,它会起作用:
Bareword "something" not allowed while "strict subs" in use at /tmp/heredoc.pl line 7.
syntax error at /tmp/heredoc.pl line 10, near "FOO_BAR
close"
/tmp/heredoc.pl had compilation errors.
Run Code Online (Sandbox Code Playgroud)
也许真正的陷阱是以下语句perlop(1)
:
There may not be a space between the "<<" and the identifier,
unless the identifier is explicitly quoted. (...)
Run Code Online (Sandbox Code Playgroud)