Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

heredoc

perl

I seem to be having a hard time getting my here-document to work properly. I have a chunk of text that I need stuffed into a variable and remain un-interpolated.

Here's what I have:

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

Which gives me

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.

However, the following works as expected:

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

What am I doing wrong?

like image 785
Mr. Llama Avatar asked Dec 11 '22 22:12

Mr. Llama


2 Answers

You need to assign the string using the assignment operator to form a complete statement:

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
like image 78
Platinum Azure Avatar answered Jan 06 '23 17:01

Platinum Azure


You missed out the = sign:

my $move_func = <<'FUNC';
like image 43
Alnitak Avatar answered Jan 06 '23 18:01

Alnitak