1. Perl
  2. Syntax
  3. string
  4. here

Escape sequence of double quoted strings

Here are the escape sequences that can be used in double-quoted strings.

Escape sequence corresponding to ASCII code

Frequently used ones are a line break "\n" and tabs "\t".

< th> ASCII
\a 7 07 BEL Alarm or Bell
\b 8 08 BS Backspace
\e 27 1B ESC Escape Sequence
\f 12 0C FF form feed
\n 10 0A LF Line feed
\r 13 0D CR Carriage return
\t 9 09 TAB Tab

This is an example using the escape sequence of tabs and a line break.

# Use tabs and a line break
my $line = "ID\tName\tPrice\n";

Occasional escape sequences

I also sometimes use escape sequences that represent double quotes "\" "and backslashes themselves" \\ ".

\" "
\\ \

Notes on line break "\n"

There is one caveat regarding a line break "\n".

In the source code of the program, "\n" is a single character and represents "LF" in ASCII code and "0A" in hexadecimal. This matches the Linx/Unix line feed code.

One thing to keep in mind is that Perl's I/O layer automatically converts to OS line feed code when outputting to standard output or files.

"\n" is converted to a two-character line feed code "0D 0A" on Windows. On Unix/Linux/macOS, it is "0A" without conversion.

# "0D 0A" on Windows, "0A" on Unix/Linux/Mac
print "Hello\n";

To avoid this conversion, use escape sequences that directly specify the ASCII code. How to specify the ASCII code directly is explained below.

Escape sequence that directly describes ASCII code

There are also escape sequences that allow you to write the ASCII code itself in hexadecimal by starting with "\x".

# Specify ASCII code directly in hexadecimal to represent HTTP protocol a line break
my $message = "Hello\x0D\x0A";
print $message;

The above example is an example that expresses the line feed code in the HTTP protocol because it is an ASCII hexadecimal sequence of "D" and "A". The 0 after the "\x" is not required, but it is included according to the convention of representing ASCII codes in 2-digit hexadecimal numbers.

Document with all escape sequences

Below is the Perl documentation with all the escape sequences.

Although it covers all the escape sequences of a regular expression, the escape sequences of double-quoted strings are included in the escape sequences of a regular expression, so let's refer only to the escape sequences of the part related to double-quoted strings.

Related Informatrion