细说各种开发语言的Heredoc

Heredoc是定义多行字符串,同时保持原始缩进和格式的一种方法。这用于嵌入诸如SQL或HTML之类的代码片段。

Heredoc

PHP Heredoc

人们能够轻松地从PHP内编写大量文本,而又不需要转义,开发了heredoc语法,我们可以使用字符串“ EOT”(文本结尾)作为分隔符,这意味着我们可以在文本正文中自由使用双引号和单引号-仅当键入EOT时字符串才结束。

<?php
$mystring = <<<EOT     This is some PHP text.
    It is completely free
    I can use "double quotes"
    and 'single quotes',
    plus $variables too, which will
    be properly converted to their values,
    you can even type EOT, as long as it
    is not alone on a line, like this: 
EOT;
?>

注意一下几点:

1.开始和结束部分都相同的字符串如EOF,EOT;
2.开始标记后不能出现空格或多余的字符;
3.位于开始标记和结束标记之间的变量可以被正常解析;
4.结束标记必须顶头写,不能有缩进和空格,且在结束标记末尾要有分号。

参考PHP Heredoc

Ruby Heredoc

Heredoc是定义多行字符串,同时保持原始缩进和格式的一种方法。

query = <<-SQL
SELECT * FROM food
WHERE healthy = true
SQL

参考Ruby Heredoc

Shell Heredoc

Heredoc是专用代码块。它使用I / O重定向的形式将命令列表提供给交互式程序或命令,例如ftp,cat或ex文本编辑器。

cat <<-ENDOFMESSAGE
    This is line 1 of the message.
    This is line 2 of the message.
    This is line 3 of the message.
    This is line 4 of the message.
    This is the last line of the message.
ENDOFMESSAGE

ssh otherhost << EOF
  ls some_folder; 
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF

参考Shell Heredoc

Golang Heredoc

字符串文字表示通过连接一系列字符获得的字符串常量。有两种形式:原始字符串文字和解释的字符串文字。

doc := `
    Foo
    Bar
`

参考Golang Heredoc

JS Heredoc

javascript中是没有heredoc, 不过ECMAScript 6(ES6)引入了一种新型的文字,即模板文字。它们具有许多功能,其中包括变量插值,但对于这个问题最重要的是,它们可以是多行的。

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

参考链接:JS Heredoc

总结

Heredoc是一种快速处理多文本或者多命令的快捷方式,使用这种方式可以快速帮助我们进行工作开发。

MYSQL Explain执行计划优化
tmux常用命令
ajax-loader