http://www.perlmonks.org?node_id=1215134


in reply to Sort text by Chapter names

This won't make a good homework answer, but may help in a real world scenario where is is not viable to read the entire book into memory.

I do realize that RAM is so cheap these days it would need to be one hell of a book to warrant this kind of treatment :D

#! /usr/bin/env perl use strict; use warnings; use autodie; # This solution will avoid reading the entire # file into memory. First we will separate the # input into one file per chapter. # This will become a filehandle in a bit my $fh; # Create a directory for the chapter output mkdir 'chapters'; # Keep a list of all chapter names my @chapter_names; # Diamond operator reads input line by line. # This can be a file or even STDIN while (<>) { if (/^Chapter/) { close $fh if $fh; # Open a new file. # The filename is the chapter name. chomp; open $fh, '>', "chapters/$_"; push @chapter_names, $_; next; } print $fh $_; } close $fh; # Now we can sort the chapter names and # read them line by line, printing on STDOUT foreach my $chapter_name (sort @chapter_names) { open $fh, '<', "chapters/$chapter_name"; print "$chapter_name\n"; while (<$fh>) { print $_; } close $fh; unlink "chapters/$chapter_name"; } rmdir 'chapters';

Best,

Jim