【问题标题】:Why do I get syntax errors with Perl Here-Document?为什么我在使用 Perl Here-Document 时会出现语法错误?
【发布时间】:2012-09-20 12:23:09
【问题描述】:

我似乎很难让我的此处文档正常工作。我有一大段文本需要填充到变量中并保持未插值。

这是我所拥有的:

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

我做错了什么?

【问题讨论】:

  • (没有赋值,&lt;&lt; 被解释为左移运算符。)

标签: perl heredoc


【解决方案1】:

需要使用赋值运算符对字符串进行赋值,形成完整的语句:

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

【讨论】:

    【解决方案2】:

    您错过了= 标志:

    my $move_func = <<'FUNC';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 2021-11-13
      相关资源
      最近更新 更多