Triple escape apostrophes

D

dan

Solution

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/;

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

print
header,
start_html( -script => $JSCRIPT ),
start_form(),
submit( -onClick=> "alertme()" ),
end_form,
end_html
;
 
P

Paul Lalli

Solution

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/;

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

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

alert('apostrophe\'s')

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

my $JSCRIPT=<<'EOF'
whateverwhatever
EOF

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top