use warnings; use strict; my $word_a = next_from_array(); my $word_f = next_from_file(); while ( 1 ) { last unless defined $word_f and defined $word_a; if ( $word_f lt $word_a ) { $word_f = next_from_file(); } elsif ( $word_a lt $word_f ) { $word_a = next_from_array(); } else { process( current_line() ); # $word_a = next_from_array(); $word_f = next_from_file(); } } { INIT { reset_array(); } { my ( $i, @array ); sub reset_array { @array = qw( item1 item2 item4 item5 ); $i = 0; } sub next_from_array { return $i < @array ? $array[ $i++ ] : ( $i = 0, undef ); } } INIT { my $filename = shift || die "Usage: blah blah blah\n"; reset_file( $filename ); } { my ( $in, $line ); sub reset_file { my $filename = shift; use PerlIO::gzip; my $mode = '<:gzip'; open $in, $mode, $filename or die "can't read $filename: $!\n"; } sub next_from_file { local $_ = $line = <$in> and chomp; return defined $_ ? ( split /\t/ )[ -1 ] : ( reset_file(), undef ); } sub current_line { return $line; } } } sub process { local $| = 1; print shift; } __END__ #### % perl -le 'print join "\t", map 'item'.int(rand 500), 1..5 for 1..1000' \ | sort -k 5,5 | gzip > mongo.gz % perl 446183.pl mongo.gz item326 item362 item39 item84 item1 item378 item164 item305 item336 item1 item238 item431 item284 item452 item2 item115 item76 item230 item319 item4 item121 item479 item258 item301 item4 item3 item480 item187 item269 item4 item278 item327 item252 item459 item5