Merge Sort of Multiple Files

This function merges multiple sorted files into one large sorted result. It sorts in ascending order.

The program opens all the files and stores the handles in an array. It has a corresponding array that contains the current line in each file. When the end of a file is reached, it closes the file and takes its slot out of both arrays, so the sort then proceeds with one fewer file.

The handles are stored in variable names, but other than that, reading from the file is as usual in Perl. An assignment from the handle to a string reads a single line into the string, as shown in the following line:

 $firstline = <$thishandle>; ...

Get Find the Bug A Book of Incorrect Programs now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.