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");
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: here-docs vs quote operators
by brian_d_foy (Abbot) on Feb 16, 2006 at 21:33 UTC | |
by ikegami (Patriarch) on Feb 16, 2006 at 21:38 UTC | |
by Anonymous Monk on Feb 16, 2006 at 21:37 UTC | |
by chromatic (Archbishop) on Feb 16, 2006 at 23:52 UTC | |
by demerphq (Chancellor) on Feb 17, 2006 at 10:26 UTC | |
by demerphq (Chancellor) on Feb 17, 2006 at 10:24 UTC | |
by Corion (Patriarch) on Feb 16, 2006 at 21:48 UTC | |
by Anonymous Monk on Feb 16, 2006 at 22:02 UTC | |
by Corion (Patriarch) on Feb 16, 2006 at 22:13 UTC |