#! perl -slw use strict; use List::Util 'first'; sub gen_merger { my( $list, $fetch, $compare, $finish ) = @_; my @item = map $fetch->($_), @$list; my $done; return sub { return $finish if $done; my $idx = first{ $item[ $_ ] ne $finish } 0 .. $#item; my $next = $item[ $idx ]; for( $idx + 1 .. $#item ) { next if $item[ $_ ] eq $finish; my $result = $compare->( $next, $item[$_] ); #$next = $item[$_] if $result == 1; # Need to keep track of which one we use not just value ( $idx, $next ) = ( $_, $item[$_] ) if $result == 1; } $item[ $idx ] = $fetch->( $list->[ $idx ] ); #$done = 1 if ! first {$item[$_] ne $finish} $idx .. $#item; # First element of array is 0 so use defined instead of truth $done = 1 if ! defined first {$item[$_] ne $finish} $idx .. $#item; return $next; }; } my $finish = 'A val that is guaranteed not to be present in any list'; my @list; open $list[ $_-1 ], '<', "file$_" or die $! for 1 .. 9; my $fetch = sub { my $fh = shift @_; return $finish if eof $fh; return scalar <$fh>; }; my $compare = sub { my( $line1, $line2) = @_; my( $stamp1 ) = $line1 =~ /^(\d+)/; my( $stamp2 ) = $line2 =~ /^(\d+)/; return $stamp1 <=> $stamp2; }; my $next = gen_merger( \@list, $fetch, $compare, $finish ); while( 1 ) { my $item = $next->(); last if defined $item && $item eq $finish; printf "$item"; }