If I understand you correctly, you want to keep each section in place, and only sort the entries under the bracketed line. If that is the case, then one way to do that would be:

my @unsorted_input; while (my $line = <Input>) { if ($line =~ /\A\[/) { # line starts with a bracket if (@unsorted_input) { # if array has entries >>>call your sort routine here<<< print @unsorted_input; undef @unsorted_input; } print $line; # print the header line } else { # line is an entry line push @unsorted_input, $line; } } >> your sort routine << # added code per soonix's correction print @unsorted_input;

How it works: The program will keep each section heading line (with the brackets) in place. All of the other lines for that section will go into your array. Once the next section line is encountered, the program will sort the entry lines currently in the array (for the last section), print them, then print the next section line and repeat the process.

Update: I know the code looks backward, but when the first header line is encounterd, there will be no data in the array, so the array printing will be skipped and just the header line gets printed. After accumulating the entries for that section in the array, then when the next section header is encountered, the array gets printed, followed by the section header.

Update 2: Updated code per soonix's correction below

--Nick

In reply to Re: Use Perl's Sort to only sort certain lines in a file? by nlwhittle
in thread Use Perl's Sort to only sort certain lines in a file? by grahambuck

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.