文本文件中的多个排序

时间:2011-03-20 11:05:02

标签: perl

使用perl查找非大小写敏感的搜索,所以如果是“!”在行的开头检测到,新的排序开始(仅在该部分)。

[test file]
! Sort Section
!
a
g
r
e
! New Sort Section
1
2
d
3
h

变,

[test file]
! Sort Section
!
a
e
g
r
! New Sort Section
1
2
3
d
h

2 个答案:

答案 0 :(得分:2)

这是一种方法:

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
}

答案 1 :(得分:1)

另一个,使用输出文件。更重要的是,不要将整个文件加载到内存中:

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;