use strict; use warnings; use Data::Dumper; use Fatal qw[open]; my %key; open my $data, '<', 'data.txt'; while(<$data>) { chomp; $key{$_} = []; } my %line; open my $all, '<', 'all.txt'; while(<$all>) { chomp; $line{key} = $_; $line{seq} = <$all>; # read the sequence chomp $line{seq}; my ($key) = ($line{key} =~ /(Contig\d*)/); if(exists $key{$key}) { push @{$key{$key}}, $line{seq}; } } print Dumper(\%key) ."\n";