- 论坛徽章:
- 6
|
如果顺序不重要,直接sort一下行不行。。。
- #!perl
- use strict;
- use warnings;
- use autodie qw{open close};
- use Tie::File;
- sub main;
- sub get_first_column;
- main;
- sub main {
- my $file = 'a.txt';
- my $col_lino_map = +{};
- open my $fh, '<', $file;
- my $index = 0;
- while (my $line = readline $fh) {
- my $col1 = get_first_column($line);
- my $next_line = readline $fh;
- my $col2 = get_first_column($next_line);
- my $col_mark = "$col1$col2";
- if (exists $col_lino_map->{$col_mark}) {
- $col_mark = $col_mark . '1';
- }
- $col_lino_map->{$col_mark} = [$index, $index+1];
- $index += 2;
- }
- close $fh;
- tie my @lines, 'Tie::File', $file or die "fail to tie file $file$/";
- my @sorted_col_mark = sort {$a cmp $b} keys %{$col_lino_map};
- open my $out_fh, '>', 'out.txt';
- for my $col_mark (@sorted_col_mark) {
- print {$out_fh} "$lines[$_]$/" for @{$col_lino_map->{$col_mark}}
- }
- untie @lines;
- }
- sub get_first_column {
- return (split /\s+/, shift())[0];
- }
- __END__
复制代码 |
|