Perl: Quoting Strings

By Xah Lee. Date: . Last updated: .

Summary: 2 major ways to quote strings strings: single quote and double quote.

'single quote'
everything is literal.
"double quote"
Backslash is char escape. Variables are evaluated.

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」

Functions q and qq

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 []. It can also be / \ | @ and most others ASCII symbols.

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

# the following are all same
$a = q(it's good);
$b = q[it's good];
$c = q{it's good};
$d = q|it's good|;
$e =  "it's good";
$f =  'it\'s good';

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

Perl String






Data Structure

Loop, Iteration


Text Processing