use Tree::RB::XS; for(@files){ open IN, $_; while(){ /^( [^\t\n]+ )\t( [0-9]+ )$/x; # avoid backtracking $f{$1}+=$2; } } my $t= Tree::RB::XS->new(compare_fn => 'int', allow_duplicates => 1); while (my ($word, $count)= each %f) { $t->insert($count, $word); } my $iter= $t->iter; printf OUT "%s\t%s\n", reverse $iter->next_kv while !$iter->done;