in reply to Use Perl's Sort to only sort certain lines in a file?
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Use Perl's Sort to only sort certain lines in a file?
by soonix (Chancellor) on Jan 01, 2015 at 20:25 UTC | |
by nlwhittle (Beadle) on Jan 01, 2015 at 20:29 UTC | |
|
Re^2: Use Perl's Sort to only sort certain lines in a file?
by grahambuck (Acolyte) on Jan 02, 2015 at 01:01 UTC |