"print $fh <<'EOF'"中的 here-doc 问题:Perl 执行 here 文档



(根据 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(这是一个为输出打开的文件句柄,顺便说一句(,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.

怎么了?

这个问题的细节很有趣(原始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.  (...)

相关内容

最新更新