use File::Slurp; my @cats = map { chomp; map [reverse split ','], split /\|/; } read_file('your_category_file'); my %desc = map { chomp; split ',', $_, 2; } read_file('your_description_file'); my @res = map { my $d = $_; join '|', "$d,$desc{$d}", map { join ',', @$_ } grep { $_->[0] =~ /^$d?/ } @cats } keys %desc; print "$_\n" for @res; __output__ 'BB','Drinks Industry'|'BB100','Coffee Suppliers'|'BB106','Tea Suppliers' 'BL','Construction Industry'|'BL100','Plasterers'|'BL102','Fencing Companies'