my (%authors, %subjects); # and populate these hashes somehow # the sort is irrelevant, at least for the part of the code you show for my $from (keys %authors) { $authors{$from}->{$buddy}++ for my $buddy map { split /\t/ } values %subjects; }