ZetCode

Perl __DATA__ section

last modified October 20, 2026

Perl lets a script carry its own input after the code. Everything that follows a line containing __DATA__ or __END__ is not compiled; instead it is available through the DATA filehandle. This is a convenient way to ship small lookup tables, test fixtures, or sample input inside a single file.

Reading records from DATA

The DATA filehandle is read like any other, so a while loop with <DATA> processes the records one line at a time. Blank lines and comments can be skipped with a regular expression.

data_section.pl
#!/usr/bin/perl

use strict;
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";
say "$_: $by_dept{$_}" for sort keys %by_dept;

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

carol,eng,6000

The first line of the data is a comment, and the blank line is empty; both are skipped by the pattern /^\s*(#|$)/. Each remaining line is split into three fields and summed, both overall and per department. The text after __DATA__ is never compiled, so it can contain anything, including characters that would be syntax errors as code.

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

__END__ and reading the data in a package

The marker __END__ behaves the same way in the main script. Inside a module, __DATA__ is the conventional choice: the DATA handle belongs to the package that contains the marker, so Mod::DATA is read from within the module. Keep the marker in the module file that defines the package, not in the main script.

end_marker.pl
#!/usr/bin/perl

use strict;
use warnings;
use v5.34.0;

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

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

__END__
pear
apple
mango

Reading the handle in list context returns every remaining line, which is then trimmed and sorted. The __END__ marker works here because the program is the main script, where it also opens the DATA handle.

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

Best Practices

In this article we have covered the __DATA__ and __END__ markers, reading records from the DATA filehandle, and the conventions that go with them.

Source

perldata: Special Literals

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Perl tutorials.