TExcelTAD
Home › Perl › Text Processing and Reports

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:

  1. Read input line by line.
  2. Skip lines you don't care about.
  3. Split or match each line into fields.
  4. Accumulate into hashes and arrays.
  5. Print a sorted, formatted report.
perl · try it yourself
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 0
Parsed 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:

perl · try it yourself
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.75
A100   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:

perl · try it yourself
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.99
north
  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:

perl · try it yourself
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.com
Lea    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:

perl · try it yourself
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, forty
Clean: 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?

  1. Reads one character at a time
  2. Paragraph mode: each read returns a block separated by blank lines
  3. Reads the whole file
  4. Disables reading

In while (<DATA>) { chomp; ... }, what does chomp act on?

  1. Nothing
  2. $_, which holds the current line
  3. The DATA handle
  4. @ARGV

Why sort keys before printing a report?

  1. Sorting is required by printf
  2. Hash order is random, so sorting makes the report stable and readable
  3. It removes duplicates
  4. To save memory