open my $fh, '<', $file) or die "Can't read '$file': $!\n"; while(<$fh>) { write_record($fh,$headerfile) if /$start_tag/; $headerfile++; } sub write_record { my ($fh, $outfile) = @_; my %out; $. = 0; while(<$fh>) { my ($key, $value) = split; $out{$key} = $value; if ($. == 17) { open my $header, '>', $outfile or die "Can't write '$outfile': $!\n"; printf $header $headerformat, map { $_,$out{$_} } keys %out; close $header; write_detail($fh,$detailsection); $detailsection++; return; } } } sub write_detail { my ($fh, $detailfile) = @_; open my $detail, '>', $detailfile or die "Can't write to '$detailfile': $!\n"; while(<$fh>) { last if /$end_constant/; print $detail; } close $detail; }