Literal String in Perl and Python

2005-01-09

Python

Strings are enclosed using single quote or double quote. e.g.

a="this "
b='and that'
print a, b

To quote a string of multiple lines, use triple quotes. Example:

d="""this
will be printed
in 3 lines"""
print d

One can add r to front for “raw string”. That is, backslash characters will be interpreted as is, not as escapes.

c=r"this\n and that"
print c # prints a single line

Reference: Python Doc↗.

Perl

In Perl, string is written like this: «'some string ...'». Everything inside the single quote is literal, including line breaks, tabs, backslash chars.

Alternatively, string can also be written like this: «"some string ..."». When a text is quoted this way, any perl variable inside will be evaluated, and backslash escapes will also be interpreted. For example, if “$aa=4;”, then «"some string $aa ..."» will evaluate to «some string 4 ...».

«"some string ..."» can be written as «qq(some string ...)», and «'some string ...'» can be written as «q('some string ...')». The «qq()» can also be written as «qq[]», and «q()» can be written as «q[]». (so that if your text contains one of the delimiter, you can use a different delimiter avoid having to escape your text.)

# perl

$a=q(here, everything is literal, 
$what or \n or ' or " or not.);

$b=qq[here, variables $a will be
expanded, backslash act as escape \n (and "quotes" or parenthesis needn't be escaped).];

print $a, "\n";
print '-----------', "\n";
print $b, "\n";

Reference: perldoc perlop↗.

Reference: perldoc -f qq↗.


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet