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

Double Quoted Strings

A double-quoted string is a string enclosed in double-quote. In Double quote string, Variable expansions and escape sequences can be used.

my $name = "Yuki Kimoto";

# Use variable expansion and line break characters
my $message = "I'm $name\n";

# "I'm Yuki Kimoto" is displayed. With a line break
print $message;

What is variable expansion?

Variable expansion is a function that allows you to expand the contents of a variable in a string.

my $name = "Yuki Kimoto";

# Use variable expansion and line break characters
my $message = "I'm $name\n";

If you want to clarify the delimiter of the variable name, you can specify it by enclosing the variable name excluding the sigil "$" with "{}".

my $name = "Yuki Kimoto";

# Specify variable name
my $message = "I'm ${name} _foo\n";

Details are explained in the article on variable expansion.

Escape sequence of double quoted strings

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

Frequently used ones are a line break "\n", tabs "\t", double quotes "\" ", and backslashes themselves" \\ ".

Escape sequence Meaning
\n Line breaks
\t tab
\" "
\\ \

Some escape sequences allow you to write the ASCII code itself by starting with "\x".

# Specify ASCII code directly to express 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.

You can read more about it in the Double Quote String Escape Sequence article.

Relationship with regular expression literals

Variable expansion and escape sequences of double-quoted strings can be used as they are in regular expression literals.

my $name = "Yuki Kimoto";

my $message = "I'm Yuki Kimoto\tHello";

# You can use variable expansion and escape sequences in regular expression literals
if ($message =~ /$name\t/) {
  
}

One of the reasons Perl's text processing is useful is that you can use double-quoted string interpolation and escape sequences as-is in regular expression literals.

I don't use variable expansion very often, but I feel that the fact that regular expression literals are a natural extension of double-quoted strings is a natural experience.

In Perl, regular expression are built in as programming language features, and regular expression literals are also implemented as one of the language features.

Related Informatrion