my %sequences = map { $_ => undef } ( '456-3210', '4670-5490', # etc ... ); my $current; while () { chomp; # If this line is a sequence identifier ... if (/^\d+(?:-\d+)?$/) { # Clear the sequence we're parsing $current = undef; # Skip this one unless it's a sequence we're looking for next unless exists $sequences{$_}; # Mark it as the one we're reading into $current = $_; next; } next unless $current; push @{$sequences{$current}}, $_; } foreach my $key (sort keys %sequences) { print "$key:\n"; print "\t$_\n" for @{$sequences{$key}}; }