ZetCode

Perl __DATA__ section

last modified November 25, 2026 Perl 5.44

A Perl script can carry its own input after the code. When Perl reaches a line that contains only __DATA__ or __END__, it stops compiling. The text that follows is available to the program through a filehandle called DATA. This is a convenient way to ship small lookup tables, sample input, test fixtures or text templates in a single file.

The DATA handle is an ordinary filehandle, so everything from Perl read file applies to it.

Reading the DATA filehandle

The simplest program reads the embedded text line by line with the <DATA> operator, just as it would read a file.

read_data.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

while (my $line = <DATA>) {
    print "$.: $line";
}

__DATA__
Old pond in the garden,
a frog jumps in,
the sound of water.

The while loop reads one line per iteration until the end of the data. Each line keeps its trailing newline, so print is used instead of say. The special variable $. holds the number of the last line read from the handle. It counts from the __DATA__ marker, not from the top of the script.

$ perl read_data.pl
1: Old pond in the garden,
2: a frog jumps in,
3: the sound of water.

The __END__ marker

In the main script, __END__ works the same way as __DATA__. It is the older of the two markers and is often used to attach documentation after the code. Here the data is read all at once.

end_marker.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @fruits = <DATA>;
chomp @fruits;

say "count: ", scalar @fruits;
say "sorted: @{[ sort @fruits ]}";

__END__
pear
apple
mango

In list context, <DATA> returns all remaining lines. The chomp function removes the newline from every element of the array. The @{[ ... ]} construct puts the result of sort inside a double-quoted string.

$ perl end_marker.pl
count: 3
sorted: apple mango pear

Skipping comments and blank lines

The text after the marker is never compiled, so it can contain anything. It is handy to allow comments and blank lines in it, which makes the data easier to read and maintain. The program then has to skip them.

skip_comments.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

while (my $line = <DATA>) {
    next if $line =~ /^\s*#/;
    next if $line =~ /^\s*$/;

    print $line;
}

__DATA__
# servers to check
alpha.example.com

# backup machines
beta.example.com
gamma.example.com

The first pattern matches lines that start with #, optionally preceded by whitespace. The second one matches lines that contain nothing but whitespace, including the newline. The next statement skips such lines, and only the server names are printed.

$ perl skip_comments.pl
alpha.example.com
beta.example.com
gamma.example.com

Parsing records

A common use of the data section is a small table of records. Each line is split into fields, and the program computes a summary from them.

salaries.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $total = 0;
my %by_dept;

while (my $line = <DATA>) {
    chomp $line;
    next if $line =~ /^\s*(#|$)/;

    my ($name, $dept, $salary) = split /,/, $line;
    $total += $salary;
    $by_dept{$dept} += $salary;
}

say "total: $total";

for my $dept (sort keys %by_dept) {
    say "$dept: $by_dept{$dept}";
}

__DATA__
# name,dept,salary
alice,eng,5000
bob,ops,4000

carol,eng,6000

The two skip rules from the previous section are combined into a single pattern, /^\s*(#|$)/. The split function breaks each record at the commas. The salaries are added to a grand total and to a hash keyed by department. Finally, the departments are printed in alphabetical order.

$ perl salaries.pl
total: 15000
eng: 11000
ops: 4000

Reading the data twice

When the end of the data is reached, further reads return undef. To read the data again, the program must move the handle back with seek. The handle is not a separate file, though. It points into the script file itself, right after the marker.

rewind.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $start = tell DATA;

for my $pass (1, 2) {
    my $count = 0;

    while (my $line = <DATA>) {
        $count++;
    }

    say "pass $pass: $count lines";
    seek DATA, $start, 0;
}

__DATA__
one
two
three

Before reading anything, tell returns the byte position at which the data starts. After each pass, seek DATA, $start, 0 jumps back to that position. Calling seek DATA, 0, 0 would instead rewind to the start of the script, and the program would read its own source code.

$ perl rewind.pl
pass 1: 3 lines
pass 2: 3 lines

Named sections

A script has only one DATA handle, but the data can be divided into named parts by a simple convention. Here each part starts with a line of the form @@ name, a style also used by the Mojolicious framework for embedded templates.

sections.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my %templates;
my $current;

while (my $line = <DATA>) {
    if ($line =~ /^@@\s+(\w+)/) {
        $current = $1;
        next;
    }

    $templates{$current} .= $line if defined $current;
}

my %user = (name => 'Lucia', items => 3);

for my $name (sort keys %templates) {
    my $text = $templates{$name};
    $text =~ s/\{(\w+)\}/$user{$1}/g;
    print "[$name] $text";
}

__DATA__
@@ greeting
Hello there, {name}!
@@ cart
{name}, your cart holds {items} items.

The loop remembers the name of the current section in $current and appends each following line to the matching hash entry. Lines that come before the first header are ignored. The templates contain placeholders in curly braces. A substitution replaces each placeholder with the value from the %user hash.

$ perl sections.pl
[cart] Lucia, your cart holds 3 items.
[greeting] Hello there, Lucia!

Unicode text in DATA

By default, the DATA handle reads bytes. A word with accented letters encoded in UTF-8 would then appear longer than it is. The use utf8 pragma, which declares that the source file is UTF-8, also decodes the data section.

unicode_data.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

while (my $word = <DATA>) {
    chomp $word;
    say "$word has ", length $word, " characters";
}

__DATA__
čerešňa
größe
naïve

With use utf8, every word is read as a string of characters and length counts characters, not bytes. Without the pragma, the first word would be reported as 10 characters long. The binmode call encodes the output back to UTF-8. Encodings are covered in Perl UTF-8 and encoding.

$ perl unicode_data.pl
čerešňa has 7 characters
größe has 5 characters
naïve has 5 characters

Best practices

These recommendations help to use the data section clearly.

Source

perldata: Special Literals · seek · tell

In this article we have read embedded data through the DATA filehandle, skipped comments, parsed records, rewound the handle, split the data into named sections and read Unicode text from it. See also Perl read file and Perl heredoc.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.