Perl Here-文件挫折

Mr.*_*ama 2 perl heredoc

我似乎很难让我的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
Run Code Online (Sandbox Code Playgroud)

哪能给我

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.
Run Code Online (Sandbox Code Playgroud)

但是,以下工作符合预期:

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Pla*_*ure 6

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

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
Run Code Online (Sandbox Code Playgroud)

  • Sonofabitch,我不敢相信我错过了.谢谢您的帮助! (5认同)

Aln*_*tak 5

你错过了=标志:

my $move_func = <<'FUNC';
Run Code Online (Sandbox Code Playgroud)