Triple escape apostrophes

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View


Having trouble with a javascript alert which contained an apostrophe
within a perl CGI script, through trial and error I eventually found out
that triple escaping the apostrophe works. No idea why.

#!/usr/bin/perl -T
use CGI qw/:standard/;

  function alertme() {

  start_html( -script => $JSCRIPT ),
  submit( -onClick=> "alertme()" ),

Re: Triple escape apostrophes

Quoted text here. Click to load it

When you use a here-doc without any quotes around the here-doc marker,
perl interprets it as being double quoted.  So what you wrote is no
different than:

my $JSCRIPT = "  function alertme() {\n    alert('apostrophe\\'s');
\n  }\n";

Since that string is in double quotes, any backslashes in it need to
be escaped.  So your first two "\" reduce to a single backslash.
Your next "\'" reduce to a single apostrophe.  Therefore, what ends up
printed to your browser is


That single slash is needed by javascript to escape the apostrophe,
since the apostrophe is also the string delimeter.

You could reduce the number of slashes by putting single quotes around
your heredoc marker, so that Perl treats it as a single-quoted string
rather than a double-quoted string


Paul Lalli

Site Timeline