对我来说,这里的doc语法更简洁,它对于多行字符串和避免引用问题非常有用。以前我经常用它们来构造SQL查询:$sql = <<
from $tablename where id in [$order_ids_list]
and product_name = "widgets"SQL;
对我来说,与使用引号相比,引入语法错误的可能性更低:$sql = "
select *
from $tablename
where id in [$order_ids_list]
and product_name = \"widgets\"
";
另一点是避免在字符串中转义双引号:$x = "The point of the \"argument" was to illustrate the use of here documents";
上面的问题是我刚才介绍的语法错误(缺少转义引号),而不是这里的文档语法:$x = <<
EOF;
它有点风格,但我将以下规则用作用于定义字符串的单文档、双文档和此处文档的规则:单株当字符串是常量时使用引号,如
'no variables here'
双倍引用时,我可以将字符串放在单行上,并需要变量内插或嵌入单引号。
"Today is ${user}'s birthday"
这里需要格式化和变量内插的多行字符串的文档。