Text Processing and Reports
"Practical Extraction and Report Language" is what Perl was built for: read lines of text, pull out the interesting fields, aggregate them, and print a tidy report. This lesson puts the earlier pieces together into the classic patterns.
The read-parse-aggregate loop
Almost every text-processing script has the same shape:
- Read input line by line.
- Skip lines you don't care about.
- Split or match each line into fields.
- Accumulate into hashes and arrays.
- Print a sorted, formatted report.
use strict;
use warnings;
my (%bytes_by_status, %hits_by_page);
my $lines = 0;
while (my $line = <DATA>) {
chomp $line;
next unless $line =~ m{^(\S+) \S+ \S+ \[[^\]]+\] "GET (\S+) [^"]*" (\d{3}) (\d+)$};
my ($ip, $page, $status, $bytes) = ($1, $2, $3, $4);
$lines++;
$bytes_by_status{$status} += $bytes;
$hits_by_page{$page}++;
}
print "Parsed $lines requests\n\n";
print "Status Bytes\n";
printf "%-6s %6d\n", $_, $bytes_by_status{$_} for sort keys %bytes_by_status;
print "\nTop pages:\n";
my @top = sort { $hits_by_page{$b} <=> $hits_by_page{$a} || $a cmp $b } keys %hits_by_page;
printf "%3d %s\n", $hits_by_page{$_}, $_ for @top[0 .. 1];
__DATA__
10.0.0.1 - - [01/May/2024:10:00:01 +0000] "GET /index.html HTTP/1.1" 200 5120
10.0.0.2 - - [01/May/2024:10:00:05 +0000] "GET /about.html HTTP/1.1" 200 2048
10.0.0.1 - - [01/May/2024:10:01:12 +0000] "GET /missing.png HTTP/1.1" 404 312
this line is garbage and will be skipped
10.0.0.3 - - [01/May/2024:10:02:40 +0000] "GET /index.html HTTP/1.1" 200 5120
10.0.0.2 - - [01/May/2024:10:03:00 +0000] "GET /index.html HTTP/1.1" 304 0Parsed 5 requests
Status Bytes
200 12288
304 0
404 312
Top pages:
3 /index.html
1 /about.html
Using m{...} as the delimiter avoids escaping the many / and " characters in the pattern.
Fixed-width and column data
Some data comes in fixed-width columns. unpack with an A template slices such lines quickly and trims trailing spaces:
use strict;
use warnings;
my @rows;
while (my $line = <DATA>) {
chomp $line;
my ($code, $name, $qty, $price) = unpack "A6 A12 A4 A8", $line;
push @rows, { code => $code, name => $name, qty => $qty, price => $price };
}
my $grand = 0;
for my $r (@rows) {
my $total = $r->{qty} * $r->{price};
$grand += $total;
printf "%-6s %-11s %3d x %6.2f = %8.2f\n", @$r{qw(code name qty price)}, $total;
}
printf "%33s %8.2f\n", "TOTAL", $grand;
__DATA__
A100 Hammer 2 12.50
B220 Screwdriver 10 3.20
C305 Tape 4 1.75A100 Hammer 2 x 12.50 = 25.00
B220 Screwdriver 10 x 3.20 = 32.00
C305 Tape 4 x 1.75 = 7.00
TOTAL 64.00
Grouping and multi-level reports
A hash of hashes groups data by two keys. Here, sales are summarised per region and per product, with subtotals:
use strict;
use warnings;
my %sales;
while (<DATA>) {
chomp;
my ($region, $product, $amount) = split /,/;
$sales{$region}{$product} += $amount;
}
my $grand = 0;
for my $region (sort keys %sales) {
print "$region\n";
my $subtotal = 0;
for my $product (sort keys %{ $sales{$region} }) {
my $amount = $sales{$region}{$product};
printf " %-8s %7.2f\n", $product, $amount;
$subtotal += $amount;
}
printf " %-8s %7.2f\n\n", "subtotal", $subtotal;
$grand += $subtotal;
}
printf "%-10s %7.2f\n", "GRAND", $grand;
__DATA__
north,widgets,120.00
south,gadgets,80.50
north,gadgets,45.25
north,widgets,30.00
south,widgets,99.99north
gadgets 45.25
widgets 150.00
subtotal 195.25
south
gadgets 80.50
widgets 99.99
subtotal 180.49
GRAND 375.74
while (<DATA>) with no variable reads each line into $_, and chomp and split then work on $_ by default.
Paragraph mode and records
$/ (the input record separator) does not have to be a newline. Setting it to "" switches on paragraph mode, where each read returns a block of lines separated by blank lines. That is perfect for record-style data:
use strict;
use warnings;
local $/ = ""; # paragraph mode
my @people;
while (my $record = <DATA>) {
my %field = $record =~ /^(\w+):\s*(.*?)\s*$/mg;
push @people, \%field;
}
for my $p (sort { $a->{name} cmp $b->{name} } @people) {
printf "%-6s %-12s %s\n", $p->{name}, $p->{role}, $p->{email} // "(no email)";
}
__DATA__
name: Zara
role: designer
email: zara@example.com
name: Omar
role: developer
name: Lea
role: manager
email: lea@example.comLea manager lea@example.com
Omar developer (no email)
Zara designer zara@example.com
Validating and cleaning input
Real data is messy. Normalise it before you use it, and count what you reject:
use strict;
use warnings;
my (@clean, %rejected);
while (my $line = <DATA>) {
chomp $line;
$line =~ s/^\s+|\s+$//g; # trim
next if $line eq '';
my ($email, $age) = split /\s*[,;]\s*/, $line;
$email = lc $email;
if ($email !~ /^[\w.+-]+@[\w-]+(\.[\w-]+)+$/) { $rejected{"bad email"}++; next }
if (!defined $age || $age !~ /^\d+$/) { $rejected{"bad age"}++; next }
push @clean, "$email ($age)";
}
print "Clean: $_\n" for @clean;
print "Rejected $_: $rejected{$_}\n" for sort keys %rejected;
__DATA__
Ana@Example.COM , 34
bob@example ; 41
carl@mail.example.org;29
dina@example.com, fortyClean: ana@example.com (34)
Clean: carl@mail.example.org (29)
Rejected bad age: 1
Rejected bad email: 1
Note: A program can only have one
__DATA__section, which is why each example here is its own little program.
Test yourself
What does setting $/ = "" do?
- Reads one character at a time
- Paragraph mode: each read returns a block separated by blank lines
- Reads the whole file
- Disables reading
In while (<DATA>) { chomp; ... }, what does chomp act on?
- Nothing
$_, which holds the current line- The DATA handle
@ARGV
Why sort keys before printing a report?
- Sorting is required by printf
- Hash order is random, so sorting makes the report stable and readable
- It removes duplicates
- To save memory