in reply to Simple but not elegant ?

If your records can't be multiline, as your regex seems to imply, you can read the file line by line and populate a hash like this:

use v5.14; use Data::Dumper; my %header; LINE: while (<DATA>) # reading line by line { chomp; # remove the \n at the end if (/^(H\d\d)(.*)/) # ^ beginning of string { $header{$1} = $2; } else { last LINE; # Stop running the LINE loop } } print Dumper \%header; __DATA__ H00 H01 Hi H02 Hello H03 Bonjour D01 D02
If your records can be multiline, you may want to read about $/ or the input record separator, and the /m modifier (which will make ^ match the beginning of any line, not just the beginning of the string). The logic may still be the same.