#!/usr/bin/perl use strict; use warnings; use List::Util 'first'; my $finish = 'The end is near'; my @list; for (glob('source_part_??')) { open(my $fh, '<', $_) or die "Unable to open '$_' for reading: $!"; push @list, $fh; } my $fetch = sub { my ($fh) = @_; return $finish if eof $fh; return scalar <$fh>; }; my $compare = sub {$_[0] <=> $_[1]}; my $next = gen_merger(\@list, $fetch, $compare, $finish); while (1) { my $item = $next->(); last if defined $item && $item eq $finish; print "$item\n"; } 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[$_]); ($idx, $next) = ($_, $item[$_]) if $result == 1; } $item[$idx] = $fetch->($list->[$idx]); $done = 1 if ! defined first {$item[$_] ne $finish} 0 .. $#item; return $next; }; }