[thelist] What characters to 'escape' Perl?

Tobyn Baugher toby at rsux.com
Mon Feb 24 22:14:01 CST 2003


On Monday, February 24, 2003 9:46 PM -0600 Hugh Blair
<hblair at hotfootmail.com> wrote:

> My lack of Perl is showing. What characters need to be 'escaped'
> in the following type of statements? (This Is not complete, just
> representitive of the lines in this routine)

You're using single quotes, so nothing except other single quotes need
to be escaped. Single quotes don't interpolate vars. Example:

my $string = 'abcdef';
print '$string'; <- prints $string

If you want to interpolate the variables in those strings you've got
(and the \n's), then you need to use double quotes like this:

print "$string"; <- prints abcdef

You almost certainly mean to use double quotes, since without them
you're not going to get any newlines and that code snippet of yours is
going to give you an internal server error with 'premature end of
script headers' as the reason.

For double-quoted strings you need to escape double quotes in the
string as well as $ and @ symbols you wish to print literally. %
doesn't need to be escaped since whole hashes aren't usually used in
strings like that and perl assumes you mean the literal %.

Additionally, I find it easier to not use "'s when I need to print HTML
in a perl script since HTML uses so many "'s already. You can do it
like this instead:

print qq(<td width="100" bgcolor="$TableColor">\n);

which is equivalent to

print "<td width=\"100\" bgcolor=\"$TableColor\">\n";

It saves you some backslashes and looks a little more readable to me.
It's personal preference, so you're free to disagree. As with all
things Perl, TMTOWTDI.

Of course, if you find yourself printing a lot of HTML, it might be a
better idea to look into something like HTML::Template or Template
Toolkit.

Hope that helps,

Toby

--
Tobyn Baugher <toby at rsux.com>
http://www.rsux.com
aim: dieplzkthxbye  icq: 14281524  efnet: toby



More information about the thelist mailing list