Skip to content
VLSI Mentor

Perl Part I · Module 4 · Strings and Text

Escape Sequences and Special Characters

A backslash inside double quotes turns the character after it into something else — usually a character you cannot type, like a newline or a tab, and sometimes a character you can type but which would otherwise be read as syntax, like a dollar sign. Chapter 4.1 showed what happens when those fire by accident; this chapter is the list, with each entry proved to be a single character by printing its code point rather than by assertion. It also covers two families that are less widely known and genuinely useful: the escapes that change the case of the text that follows them, and the one that takes arbitrary text and makes every character in it safe to use as a literal pattern.

Foundation13 min readPerlPart IFundamentalsStringsEscapes

Part I · Module 4 · Chapter 4.3 · Escape Sequences and Special Characters

1. Two Jobs for a Backslash

Inside a double-quoted string a backslash does one of two things:

  • It names a character you cannot type. A newline, a tab, a NUL. \n is not a backslash and an n — it is one character.
  • It protects a character Perl would otherwise read as syntax. \$ is a dollar sign that does not start a variable, as Chapter 4.2 §5 needed.

Both are the same mechanism: the backslash and the character after it are replaced by one character. That replacement is what made "C:\new\table" ten characters long in Chapter 4.1 §2.

2. The Table, Measured

Each row below was produced by taking the escape's result and printing ord() of it — the character's numeric code point. A single number is the proof that the result is a single character.

Azvya Education Pvt. Ltd.VLSI Mentor
ords.pl
use strict;
use warnings;

for my $pair (["\\n", "\n"], ["\\t", "\t"], ["\\r", "\r"],
              ["\\\\", "\\"], ["\\\"", "\""], ["\\\$", "\$"],
              ["\\@", "\@"], ["\\0", "\0"], ["\\e", "\e"], ["\\a", "\a"]) {
    printf "%-6s length=%d  ord=%d\n", $pair->[0], length($pair->[1]), ord($pair->[1]);
}
Azvya Education Pvt. Ltd.VLSI Mentor
Captured output
\n     length=1  ord=10
\t     length=1  ord=9
\r     length=1  ord=13
\\     length=1  ord=92
\"     length=1  ord=34
\$     length=1  ord=36
\@     length=1  ord=64
\0     length=1  ord=0
\e     length=1  ord=27
\a     length=1  ord=7

Every one is length=1. Read as a reference:

EscapeCharacterCode pointWhen you need it
\nnewline10ending a line of output
\ttab9separating columns
\rcarriage return13rewriting a progress line; part of a Windows line ending
\\backslash92a literal backslash in a double-quoted string
\"double quote34a quote inside a double-quoted string
\$dollar sign36a literal $ — Chapter 4.2
\@at sign64a literal @, as in an address
\0NUL0rarely; it terminates strings in C, not in Perl
\eescape27the first character of a terminal colour code
\abell7an audible alert; usually unwelcome

The first two are the ones you will use constantly. The rest are worth recognising, and \r is worth a note of its own.

3. Naming a Character by Its Number

When you need a character that has no named escape, give its code point in hexadecimal:

Azvya Education Pvt. Ltd.VLSI Mentor
hex.pl
use strict;
use warnings;

print "\x41\n";
print "\x{48}\x{69}\n";
Azvya Education Pvt. Ltd.VLSI Mentor
Captured output
A
Hi
  • \x41 takes exactly two hex digits. 41 is 65, which is A.
  • \x{...} takes any number of digits inside braces, which is what you need above 255.

A character beyond the ASCII range works, with one extra consequence worth disclosing:

Azvya Education Pvt. Ltd.VLSI Mentor
wide.pl
use strict;
use warnings;

printf "tick: %s\n", "\x{2713}";
Azvya Education Pvt. Ltd.VLSI Mentor
Captured output — STDOUT
tick: ✓
Azvya Education Pvt. Ltd.VLSI Mentor
Captured output — STDERR
Wide character in printf at wide.pl line 4.

The character printed correctly and Perl warned anyway. The warning is not about the escape being wrong — it is about writing a character above 255 to a stream that has not been told it is handling text in a multi-byte encoding. Output encoding is Module 12's subject. For Part I, the practical note is that non-ASCII output warns until the stream is configured, and that engineering scripts rarely need it: a report in plain ASCII is the safe default and sorts and compares predictably.

4. The Case Escapes

These are under-used and worth knowing, partly because they appear in inherited scripts and look like mistakes.

Azvya Education Pvt. Ltd.VLSI Mentor
case-escapes.pl
use strict;
use warnings;

my $s = "alu_top";

print "upper all : \U$s\E\n";
print "upper one : \u$s\n";
print "lower all : \LALU_TOP\E\n";
print "lower one : \lALU\n";
Azvya Education Pvt. Ltd.VLSI Mentor
Captured output
upper all : ALU_TOP
upper one : Alu_top
lower all : alu_top
lower one : aLU
EscapeEffectEnds at
\Uuppercase everything after it\E or end of string
\Llowercase everything after it\E or end of string
\uuppercase the next character only—
\llowercase the next character only—

Note \lALU gave aLU — only the A changed. The single-character forms are easy to misread as applying to the whole word.

\E ends the effect of \U or \L. Forgetting it means the rest of the string is affected, which is the usual bug with these.

These do the same work as the uc, lc, ucfirst and lcfirst functions, which Chapter 4.6 covers. The functions are generally clearer, because the transformation is visible at the start of the expression rather than buried in the middle of a quoted string. Use the escapes when you are already building a string and want one piece of it cased differently.

5. \Q — Making Text Safe to Match

This one has a real payoff and is worth meeting before you need it.

Azvya Education Pvt. Ltd.VLSI Mentor
quotemeta.pl
use strict;
use warnings;

my $version = "v1.2.3 (beta)";

print "raw      : $version\n";
print "quoted   : \Q$version\E\n";
Azvya Education Pvt. Ltd.VLSI Mentor
Captured output
raw      : v1.2.3 (beta)
quoted   : v1\.2\.3\ \(beta\)

\Q puts a backslash in front of every character that is not a letter, digit or underscore. Look at what got escaped: the dots, the parentheses — and the space.

Why that matters: in a regular expression, . means "any character" and ( opens a group. So a version string used directly as a pattern would match things it should not, and an unbalanced parenthesis in the data would make the pattern fail to compile at all. \Q turns arbitrary text into a pattern that matches exactly itself.

Regular expressions are Module 11's subject and nothing here requires them. The reason to know \Q now is the rule it represents: text that came from outside your program is not safe to use as a pattern until it has been quoted. A tool name, a path, a version read from a log — any of these can contain punctuation that means something in a pattern.

6. Why This Matters in Engineering Work

Column alignment in a report. \t between fields is the quickest way to line up a table, and it is also fragile: a tab is one character that renders as a variable amount of space depending on the viewer. For a report that must line up reliably, Chapter 4.8 and fixed widths are the better tool. Use \t for quick output, printf for anything a colleague will read.

Windows line endings in input. A log written on one platform and parsed on another carries \r. This is the single most common cause of a string comparison that is visibly correct and still fails, and knowing the character exists is most of the diagnosis.

Literal sigils in messages. Costs, addresses, shell variable names in documentation strings — \$ and \@ are the escapes, and Chapter 4.1 §5's alternative of single-quoting the whole string is often cleaner.

Terminal colour, used sparingly. \e[ begins an ANSI sequence, which is how a script highlights a failure count in red. Worth knowing it is possible; worth also knowing that the escape codes end up in the file when output is redirected, which turns a log into something hard to read. Colour only when writing to a terminal.

7. Common Mistakes

Assuming \n is two characters. It is one, code point 10. §2 measures it.

Using a backslash escape in single quotes. Only \\ and \' exist there — Chapter 4.1 §4.

Forgetting \E after \U or \L. The effect runs to the end of the string.

Thinking \u uppercases a word. It uppercases one character. \U does the rest.

Using unquoted external text as a pattern. Punctuation in the data changes or breaks the pattern. \Q is the fix.

Writing a non-ASCII character and ignoring the warning. The output is right and the stream is unconfigured; for Part I scripts, prefer ASCII.

Relying on \t for alignment in a shared report. Tab width varies by viewer. Use fixed-width formatting.

8. Exercise

Exercise 1 — prove they are single characters. Run the §2 script. Then pick three escapes and, for each, write one sentence stating the code point and what a length() of 1 tells you about Chapter 4.1's path example.

Exercise 2 — build a tab-separated row. Print three fields separated by \t and ending in \n. Then measure the total string length and account for every character.

Exercise 3 — the hidden carriage return. Create a string "PASS\r" and compare it with "PASS" using eq. Record the result, then print both with their lengths and explain why the printed forms look identical.

Exercise 4 — the case escapes. Predict each before running, with my $s = "fifo_wr";: "\U$s\E", "\u$s", "\U$s", "\u${s}_TOP". Then run them and say which one demonstrates why \E matters.

Exercise 5 — hex by number. Print the characters with code points 0x50, 0x41, 0x53, 0x53 using \x escapes, and confirm what word you get. Then do the same with \x{...} and say when the braced form is required.

Exercise 6 — make text pattern-safe. Take my $tool = "dc_shell-2023.12 (64-bit)"; and print it with \Q. List every character that gained a backslash, and say which two of them would have changed the meaning if the string had been used as a pattern unquoted.

9. Summary

  • A backslash escape produces one character — proved by ord() and length() in §2.
  • \n is 10 and \t is 9; these two carry most everyday output.
  • \r is 13, is invisible when printed, and is why a correct-looking comparison against data from a Windows file can fail — Chapter 4.9 handles it.
  • \$ and \@ protect a sigil from interpolation.
  • \x41 and \x{...} name a character by code point; above 255 the output warns until the stream is configured for encoding.
  • \U, \L run until \E; \u, \l affect one character only.
  • \Q escapes every non-word character, spaces included, which is how arbitrary text becomes safe to use as a literal pattern.

Chapter 4.4 covers the alternative quoting operators, which let you pick your own delimiter when a string is full of quotes or backslashes — and includes one of Perl's most frequently mistyped constructs.

Where this fits

Part of the Perl curriculum.