Reputation: 2217
Looking for a non-case sensitive search using perl, So if a "!" is detected at the start of the line, a new sort begins (only on the section).
[test file]
! Sort Section
!
a
g
r
e
! New Sort Section
1
2
d
3
h
becomes,
[test file]
! Sort Section
!
a
e
g
r
! New Sort Section
1
2
3
d
h
Upvotes: 0
Views: 109
Reputation: 15264
Another one, using an output file. More importantly, not loading an entire file into memory:
use strict;
use warnings;
sub output {
my( $lines, $fh ) = @_;
return unless @$lines;
print $fh shift @$lines; # print first line
print $fh sort { lc $a cmp lc $b } @$lines; # print rest
return;
}
# ==== main ============================================================
my $filename = shift or die 'filename!';
my $outfn = "$filename.out";
die "output file $outfn already exists, aborting\n" if -e $outfn;
# prereqs okay, set up input, output and sort buffer
open my $fh, '<', $filename or die "open $filename: $!";
open my $fhout, '>', $outfn or die "open $outfn: $!";
my $current = [];
# process data
while ( <$fh> ) {
if ( m/^!/ ) {
output $current, $fhout;
$current = [ $_ ];
}
else {
push @$current, $_;
}
}
output $current, $fhout;
close $fhout;
close $fh;
Upvotes: 1
Reputation: 15264
Here's one way to do it:
use strict;
use warnings;
my $filename = shift or die 'filename!';
my @sections;
my $current;
# input
open my $fh, '<', $filename or die "open $filename: $!";
while ( <$fh> ) {
if ( m/^!/ ) {
$current = [ $_ ];
push @sections, $current;
}
else {
push @$current, $_;
}
}
close $fh;
# output
for ( @sections ) {
print shift @$_; # print first line
print sort @$_; # print rest
}
Upvotes: 2