I did not notice
afoken's note until after I wrote this code, so here it is.
To do this right, you need a slightly complicated structure - a hash-of-arrays.
#!/bin/perl -w
use strict;
use warnings;
my @filenames = ("file1.txt", "file2.txt");
my %result; # Hash of arrays
for my $fname(@filenames){
my $currentheader = "";
open my $f, "<", $fname or die "Cannot open '$fname' : $!";
while (my $line = <$f>){
chomp $line;
next unless length($line); # Skip blank lines
if ($line=~/NAME/){
$currentheader = $line;
next;
}
push @{ $result{$currentheader} }, $line;
}
}
# Print results
for my $currentheader(sort keys %result){
print "\n$currentheader\n";
print "$_\n" for @{ $result{$currentheader} };
}
Once it hits the fan, the only rational choice is to sweep it up, package it, and sell it as fertilizer.