XuLaLa.Tech

首页客户端下载Windows 使用V2Ray 教程SSR 教程Clash 教程

细说各种开发语言的Heredoc

2025.04.09

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

文章目录

  • 1 PHP Heredoc
  • 2 Ruby Heredoc
  • 3 Shell Heredoc
  • 4 Golang Heredoc
  • 5 JS Heredoc
  • 6 总结

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是一种快速处理多文本或者多命令的快捷方式,使用这种方式可以快速帮助我们进行工作开发。

© 2010-2022 XuLaLa 保留所有权利 本站由 WordPress 强力驱动
请求次数:69 次,加载用时:0.665 秒,内存占用:32.19 MB