在任何支持它们的语言中,heredoc都是制作大型字符串文字的便捷方式.
采取以下设计的Ruby脚本,它带有你的名字并输出一个C程序的源代码,告诉你你好:
#!/usr/bin/env ruby
name = $*[0]
unless name
$stderr.puts "Please supply a name as the first argument to the program"
exit 1
end
source = <<EOF
#include <stdio.h>
int main()
{
puts("Hello, #{name}!");
return 0;
}
EOF
puts source
Run Code Online (Sandbox Code Playgroud)
除了heredoc之外,制作源代码的另一个选择是逐行指定它,这变得乏味且可能容易出错(特别是当你有嵌入式引号时).