Perl: Quoting Strings

By Xah Lee. Date: . Last updated: .

Use single quote for literal string.

# -*- coding: utf-8 -*-
# perl

# use single quote for literal string
$a = 'this and
print $a; # prints 2 lines

To have characters \n for newline and \t for tab, use double quote.

# -*- coding: utf-8 -*-
# perl

$a = "this\nand that";
print $a; # prints 2 lines

When double quote is used, variables inside the string will be evaluated.

# -*- coding: utf-8 -*-
# perl

$a = 4;
$b = "this is $a";
print $b; # prints 「this is 4」

Basically, perl has 2 modes of strings: single quote and double quote. In single quote mode, everything is literal. In double quote mode, backslash is a char escape mechanism, and variables inside it will be evaluated.

“q()” and “qq()” Functions

You can also use the syntax q(this n that), which is equivalent to 'this n that'. The parenthesis can be curly brackets {} or square brackets [].

# the following are all same
$a = q(this 'n' that);
$b = q[this 'n' that];
$c = "this 'n' that";
$d = 'this \'n\' that';
print $a, "\n";
print $b, "\n";
print $c, "\n";
print $d, "\n";

Similarly, "…" is same as qq(…).

# -*- coding: utf-8 -*-
# perl

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

$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";



Text Processing