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


In reply to Re: Sort text by Chapter names by jimpudar
in thread Sort text by Chapter names by Bman70

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.