Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is print <<EOF; and how is it working? [duplicate]

Tags:

perl

Possible Duplicate:
Help me understand this Perl statement with <<'ESQ'

What is the statement in https://stackoverflow.com/questions/4151279/perl-print-eof doing exactly? I came across the previous post but didn't understand what he is trying to explain. What is that PETE? Can anyone explain every line? How is the code is working?

print <<EOF;
This is
a multiline
string
EOF

print <<PETE;
This is
a multiline
string
PETE

What is the difference and similarity between these two? In place of PETE I have used many other words like DOG and it works the same every time.

like image 210
beastboy Avatar asked Aug 14 '12 08:08

beastboy


2 Answers

This is called a here-doc. It basically grabs everything from the next line up until an end marker line and presents that as standard input to the program you're running. The end marker line is controlled by the text following the <<.

As an example, in bash (which I'm more familiar with than Perl), the command:

cat <<EOF
hello
goodbye
EOF

will run cat and then send two lines to its standard input (the hello and goodbye lines). Perl also has this feature though the syntax is slightly different (as you would expect, given it's a different language). Still, it's close enough for the explanation to still hold.

Wikipedia has an entry for this which you probably would have found had you known it was called a here-doc, but otherwise it would be rather hard to figure it out.

In your particular cases, there is no difference between using EOF and PETE, there's a relationship between the heredoc marker (the bit following <<) and the end of standard input.

For example, if one of your input lines was EOF, you couldn't really use that as a marker since the standard input would be terminated prematurely:

cat <<EOF
This section contains the line ...
EOF
but then has more stuff
and this line following is the real ...
EOF

In that case, you could use PETE (or anything else that doesn't appear in the text on its own line).

There are other options such as using quotes around the marker (so the indentation can look better) and the use of single or double quotes to control variable substitution.

If you go to the perlop page and search for <<EOF, it will hopefully all become clear.

like image 181
paxdiablo Avatar answered Nov 16 '22 04:11

paxdiablo


See Quote and Quote-like Operators (it's pretty well explained).

like image 31
Vidul Avatar answered Nov 16 '22 06:11

Vidul