(根据https://stackoverflow.com/a/17479551/6607497的说法,它应该可以工作,但没有)我有一些代码如下:
use strict;
use warnings;
if (open(my $fh, '>', '/tmp/test')) {
print $fh << 'TAG';
BEGIN {
something;
}
TAG
close($fh);
}如果我省略了$fh (这是一个为输出而打开的文件句柄,BTW),那么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.怎么啦?
发布于 2020-06-29 19:06:04
这个问题的细节很有趣(最初的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);
}perl -c说:/tmp/heredoc.pl syntax OK,但是什么都没有输出!
如果我在<<之前添加$fh,我会得到这个错误:
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.最后,如果我删除'FOO_BAR'前面的空格,它会起作用:
#!/usr/bin/perl
use strict;
use warnings;
if (open(my $fh, '>', '/tmp/test')) {
print $fh <<'FOO_BAR';
BEGIN {
something;
}
FOO_BAR
close($fh);
}
> perl -c /tmp/heredoc.pl
/tmp/heredoc.pl syntax OK
> perl /tmp/heredoc.pl
> cat /tmp/test
BEGIN {
something;
}也许真正的陷阱在于perlop(1)中的语句
There may not be a space between the "<<" and the identifier,
unless the identifier is explicitly quoted. (...)https://stackoverflow.com/questions/62636057
复制相似问题