Sometimes, blocks of code need to be quoted for later evaluation. One could use a quote operator, or a here-doc. In the past, I've claimed that here-docs make things easier to escape. Here's the basis for my claim, complete with (simplified) realistic examples.
When using here-docs, extra slashes are never necessary. You could write your code exactly as if it wasn't in a here-doc at all.
When using the quote operator, backslashes must be doubled when they occur in front of another backslash and when they occur in front of the string delimiter.
Obviously, a backslash must be added before an unbalanced delimiter when using the quote operator. However, unbalanced delimiters are rare, and omitting the slash will likely cause an (easy to detect) compile-time error.
$hd = <<'__EOS__'; '\\\\' =~ /^..$/ __EOS__ $q = q[ '\\\\' =~ /^..$/ ]; $q2 = q[ '\\\\\\\\' =~ /^..$/ ]; print($hd); print(eval($hd) ?1:0, "\n"); print($q ); print(eval($q ) ?1:0, "\n"); print($q2); print(eval($q2) ?1:0, "\n"); $hd = <<'__EOS__'; '[]' =~ /\[\]/ __EOS__ $q = q[ '[]' =~ /\[\]/ ]; $q2 = q[ '[]' =~ /\\[\\]/ ]; print($hd); print(eval($hd) ?1:0, "\n"); print($q ); print(eval($q ) ?1:0, "\n"); print($q2); print(eval($q2) ?1:0, "\n"); $hd = <<'__EOS__'; 'funny' # :-] __EOS__ # Syntax error # ------------ # $q = q[ # 'funny' # :-] # ]; $q2 = q[ 'funny' # :-\] ]; print($hd); print(eval($hd) ?1:0, "\n"); print($q2); print(eval($q2) ?1:0, "\n");
When interpolation is necessary, there's no difference between here-docs and the quote operator.
Obviously, a backslash must be added before an unbalanced delimiter when using the quote operator. However, unbalanced delimiters are rare, and omitting the slash will likely cause an (easy to detect) compile-time error.
$hd = <<"__EOS__"; '\\\\\\\\' =~ /^..\$/ __EOS__ $qq = qq[ '\\\\\\\\' =~ /^..\$/ ]; print($hd); print(eval($hd) ?1:0, "\n"); print($qq); print(eval($qq) ?1:0, "\n"); $hd = <<"__EOS__"; '[]' =~ /\\[\\]/ __EOS__ $qq = qq[ '[]' =~ /\\[\\]/ ]; print($hd); print(eval($hd) ?1:0, "\n"); print($qq); print(eval($qq) ?1:0, "\n"); $hd = <<"__EOS__"; 'funny' # :-] __EOS__ # Syntax error # ------------ # $qq = qq[ # 'funny' # :-] # ]; $qq2 = qq[ 'funny' # :-\] ]; print($hd ); print(eval($hd ) ?1:0, "\n"); print($qq2); print(eval($qq2) ?1:0, "\n");
In reply to here-docs vs quote operators by ikegami
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |