#!/usr/bin/env perl use strict; use warnings; use 5.010; use Array::Heap::PriorityQueue::String; my @file_names = qw( in1 in2 in3 ); my @fh; my $heap = Array::Heap::PriorityQueue::String->new; for (0 .. $#file_names) { my $fn = $file_names[$_]; open my $new_fh, '<', $fn or die "Unable to open $fn: $!\n"; $fh[$_] = $new_fh; add_from_fh_id($_); } my ($current_word) = split /\s+/, $heap->peek; my $total = 0; while (my $item = $heap->get) { my ($word, $count, $fh_id) = split /\s+/, $item; if ($word eq $current_word) { $total += $count; } else { say "$current_word\t$total"; $current_word = $word; $total = $count; } add_from_fh_id($fh_id); } say "$current_word\t$total"; sub add_from_fh_id { my $fh_id = shift; my $read_from = $fh[$fh_id]; my $next_line = <$read_from>; if ($next_line) { chomp $next_line; $heap->add("$next_line $fh_id"); } } #### bar 70 blah 69 foo 146 life 42 word 81 yada 3