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

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email