# Somewhere at the top my $chunk = qr/[A-Z0-9()-]{2,15})\s+([A-Z0-9()-]{7}/;\ #... # then instead of your loop body if (/^(\d{1,5})\s+($chunk)/g) { my $1st = $1; my $subrecord_id = 1; ++$record_count; while (/\G($chunk)/g) { print OUTFILE "$record_count\t$1st\t$subrecord_id\t$_\n"; $subrecord_id++; } }