Perl Tutorial
Fundamentals
Input and Output
Control Flow
Arrays and Lists
Hash
Scalars
Strings
Object Oriented Programming in Perl
Subroutines
Regular Expressions
File Handling
Context Sensitivity
CGI Programming
Misc
In Perl, multi-line strings can be represented in a variety of ways, but one of the most idiomatic and flexible methods is the "here document" syntax, often referred to as a "heredoc". A heredoc allows you to define a string across multiple lines without needing to constantly break and concatenate the string, making it an ideal solution for long strings, configuration data, or multi-line output. This tutorial will guide you on how to use the heredoc syntax in Perl.
A heredoc starts with <<
followed by an identifier of your choosing. The string then starts on the next line and continues until the identifier is reached again.
my $string = <<END_TEXT; This is a multi-line string. You can add as many lines as you want. The string ends when the identifier is reached again. END_TEXT print $string;
The output will be:
This is a multi-line string. You can add as many lines as you want. The string ends when the identifier is reached again.
You can use variables inside a heredoc, and they will be interpolated:
my $name = "Alice"; my $message = <<GREETING; Hello, $name! Welcome to the world of Perl heredocs. GREETING print $message;
The output:
Hello, Alice! Welcome to the world of Perl heredocs.
If you want the content inside the heredoc to be treated as a single-quoted string (where variable interpolation does not occur), you can enclose the identifier in single quotes:
my $name = "Alice"; my $message = <<'GREETING'; Hello, $name! Variables won't be interpolated here. GREETING print $message;
The output:
Hello, $name! Variables won't be interpolated here.
With Perl 5.26 and newer, you can use the <<~
syntax to create a heredoc with indented content:
my $string = <<~'TEXT'; This is an indented heredoc. Each line's content will be shifted to the left to remove the leading whitespace. TEXT print $string;
Output:
This is an indented heredoc. Each line's content will be shifted to the left to remove the leading whitespace.
Heredocs are useful for:
The ending identifier must start at the beginning of the line (no whitespace before it) and be followed immediately by a newline or a semicolon.
It's common to use all-uppercase identifiers for heredocs, but it's not a strict requirement.
Since the heredoc ending identifier must appear by itself on its own line, it's important to ensure that it doesn't accidentally appear within the text of the heredoc.
The heredoc syntax in Perl provides an elegant way to handle multi-line strings, making your scripts cleaner and more readable. By understanding the nuances of heredocs and how to leverage them effectively, you can simplify the way you handle large strings in your Perl code.