1. Perl
  2. Operators
  3. here

Here - Document - Easily create multi - line strings

You can use here document to describe multiple strings in an easy-to-understand way.

my $text = <<'EOS';
aaaa
iiii
uuuu
EOS

Here-documents allow you to assign a string on a line between <<'EOS' and EOS to the string, preserving a line break.

Pay attention to the position of the semicolon. After the last EOS, there is no semicolon, there is a semicolon at the end of the first line.

The part called EOS can be any string. This example uses EOS to mean "End Of String".

Expand variable in here documents

If you change <<'EOS' to << "EOS", you can variable expansion in the here document.

my $message = 'Hello';

# Variable expandable here document
my $text = << "EOS";
aaaa
$message
iiii
uuuu
EOS

Even if you omit the double quotes as shown below, the variable will be expanded, but it is recommended to enclose it in double quotes so that you can clearly understand the meaning.

my $text = <<EOS;
aaaa
$message
iiii
uuuu
EOS

Example program

Here-document example.

use strict;
use warnings;

# Here document

print "1: Use here document. (No variable expansion)\n";
my $text_no_expand = <<'EOS';
aaaa
iiii
uuuu
EOS

print "$text_no_expand\n";

print "2: Use here document. (With variable expansion)\n";
my $str = "eeee";
my $text_expand = << "EOS";
$str
oooo
EOS

print "$text_expand\n";

Related Informatrion