use strict; use Data::Dumper; my (@record, $discard, %temp); open(FH, 'data') or die 'file not found'; # discard the first line $discard = ; while() { chomp; s/\cM//; if (/^\d-RECORD$/) { push @record, {%temp}; undef %temp; } elsif (/ITEMNAME-(.*)/) { $temp{name} = $1; } elsif (/ITEM \d-(.*)/) { push @{$temp{item}}, $1; } } # the last record needs to be added outside while loop push @record, {%temp}; print Dumper \@record; # print items of last record print join(', ', @{$record[-1]{item}}), "\n";