#!/usr/bin/perl use strict; use warnings; use Tie::File; my $file = 'BlastOutput.txt'; my %hash; my @sorted; my $i = 1; tie my @array,'Tie::File',$file or die $!; chomp @array; while($i < scalar(@array)-1){ push(@{$hash{$array[$i]}},$array[$i+1]); push(@sorted,$array[$i]) unless(grep{$_ eq $array[$i]}@sorted); $i += 2; } untie @array; open(my $fh,">$file") or die $!; for my $key(@sorted){ print $fh $key,"\n",join("\n",@{$hash{$key}}),"\n"; } close $fh;