Help me understand this Perl statement with <<'ESQ'

隐身守侯 提交于 2019-12-20 02:51:30

问题


substr($obj_strptime,index($strptime,"sub")+6,0) = <<'ESQ';
 shift; # package
 ....
 ....
ESQ

What is this ESQ and what is it doing here? Please help me understand these statements.


回答1:


It marks the end of a here-doc section.

EOF is more traditional than ESQ though.




回答2:


This construct is known as a here-doc (because you're getting standard input from a document here rather than an external document on the file system somewhere).

It basically reads everything from the next line up to but excluding an end marker line, and uses that as standard input to the program or command that 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.

You can basically use any suitable marker. 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 DONE (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.



来源:https://stackoverflow.com/questions/3414515/help-me-understand-this-perl-statement-with-esq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!