首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >` `print $fh <<‘EOF’`中here-doc的问题: Perl执行here doc

` `print $fh <<‘EOF’`中here-doc的问题: Perl执行here doc
EN

Stack Overflow用户
提问于 2020-06-29 18:23:16
回答 1查看 120关注 0票数 3

(根据https://stackoverflow.com/a/17479551/6607497的说法,它应该可以工作,但没有)我有一些代码如下:

代码语言:javascript
复制
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,这导致了运行时错误:

代码语言:javascript
复制
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.

怎么啦?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-29 19:06:04

这个问题的细节很有趣(最初的Perl是5.18.2,但在示例中使用了5.26.1 ):

首先是一些不使用$fh的代码

代码语言:javascript
复制
#!/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,我会得到这个错误:

代码语言:javascript
复制
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'前面的空格,它会起作用:

代码语言:javascript
复制
#!/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)中的语句

代码语言:javascript
复制
           There may not be a space between the "<<" and the identifier,
           unless the identifier is explicitly quoted.  (...)
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62636057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档