pileofrogs has asked for the wisdom of the Perl Monks concerning the following question:
What's the right way to escape a string that will be encased in quotes and then handed off to a parser of some kind?
I'm generating some javascript and I want to be confidant that my quotes won't be out of whack. Here's an example of what I do not want to do.
sub alert { my $mesg = shift; print "alert('$mesg')\n"; } alert("Don't do that!");
The "'" in "Don't" will make the resulting javascript broken.
The obvious wrong solution is to replace "'" with "\'", but that would fail if I tried to be smart and called alert("Don\'t do that!") because it would turn it into "alert('Don\\'t do that)".
So, my question to you Monks is, what is the right way?
Update:
Waitaminute.. am I overthinking this..? Will
work?sub quote { my $str = shift; # escape all slashes $str =~ s/\\/\\\\/g; # escape all single-quotes $str =~ s/'/\\'/g; return $str; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Quote Escape
by Lawliet (Curate) on Feb 06, 2009 at 23:58 UTC | |
by pileofrogs (Priest) on Feb 07, 2009 at 00:11 UTC | |
|
Re: Quote Escape
by salazar (Scribe) on Feb 07, 2009 at 03:59 UTC | |
|
Re: Quote Escape
by roboticus (Chancellor) on Feb 07, 2009 at 06:27 UTC | |
|
Re: Quote Escape
by AnomalousMonk (Archbishop) on Feb 07, 2009 at 02:31 UTC | |
|
Re: Quote Escape
by Anonymous Monk on Feb 07, 2009 at 05:26 UTC | |
by Anonymous Monk on Feb 07, 2009 at 05:41 UTC | |
|
Re: Quote Escape
by dsheroh (Monsignor) on Feb 07, 2009 at 14:41 UTC | |
by Anonymous Monk on Feb 07, 2009 at 16:39 UTC |