繁体   English   中英

为什么使用 Perl Here-Document 时会出现语法错误?

[英]Why do I get syntax errors with Perl Here-Document?

我似乎很难让我的 here-document 正常工作。 我有一大块文本需要填充到变量中并保持未插值。

这是我所拥有的:

my $move_func <<'FUNC';
function safemove
{
    if [[ ! -f $1 ]] ; then echo "Source File Not Found: $1"; return 1; fi
    if [[ ! -r $1 ]] ; then echo "Cannot Read Source File: $1"; return 2; fi
    if [[ -f $2 ]]   ; then echo "Destination File Already Exists: $1 -> $2"; return 3; fi
    mv $1 $2
}
FUNC

# Do stuff with $move_func

这给了我

Scalar found where operator expected at ./heredoc.pl line 9, near "$1 $2"
        (Missing operator before $2?)
Semicolon seems to be missing at ./heredoc.pl line 10.
syntax error at ./heredoc.pl line 6, near "if"
syntax error at ./heredoc.pl line 10, near "$1 $2
"
Execution of ./heredoc.pl aborted due to compilation errors.

但是,以下内容按预期工作:

print <<'FUNC';
function safemove
{
    if [[ ! -f $1 ]] ; then echo "Source File Not Found: $1"; return 1; fi
    if [[ ! -r $1 ]] ; then echo "Cannot Read Source File: $1"; return 2; fi
    if [[ -f $2 ]]   ; then echo "Destination File Already Exists: $1 -> $2"; return 3; fi
    mv $1 $2
}
FUNC

我究竟做错了什么?

您需要使用赋值运算符来分配字符串以形成完整的语句:

my $move_func = <<'FUNC';
function safemove
{
    if [[ ! -f $1 ]] ; then echo "Source File Not Found: $1"; return 1; fi
    if [[ ! -r $1 ]] ; then echo "Cannot Read Source File: $1"; return 2; fi
    if [[ -f $2 ]]   ; then echo "Destination File Already Exists: $1 -> $2"; return 3; fi
    mv $1 $2
}
FUNC

# Do stuff with $move_func

你错过了=符号:

my $move_func = <<'FUNC';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM