1

If I want to read multiple lines with same elements into one array or hash until reaching the next line with a different element. These elements have already been sorted so they are in the lines next to each other. For example:

1_1111  1234
1_1111  2234 
1_1111  3234
1_1112  4234
1_1112  5234
1_1112  6234
1_1112  7234
1_1113  8234
1_1113  9234

I want to read the first three lines with same element 1_1111 into one array, process it, then read the next few lines with the same element 1_1112

4

2 回答 2

1
my $key;
my @nums;
while (<>) {
   my @fields = split;
   if (@nums && $fields[0] ne $key) {
      process($key, @nums);
      @nums = ();
   }

   $key = $fields[0];
   push @nums, $fields[1];
}

process($key, @nums) if @nums;
于 2013-09-18T04:28:38.683 回答
0

您可以将文件读入数组哈希:

#!/usr/bin/perl

use strict;
use warnings;

my %hash;
while (<DATA>) {
    my ($key, $value) = split /\s+/;
    push @{ $hash{$key} }, $value;
}

__DATA__
1_1111  1234
1_1111  2234
1_1111  3234
1_1112  4234
1_1112  5234
1_1112  6234
1_1112  7234
1_1113  8234
1_1113  9234

哈希的键对应于左列中的数字,而值是右列中的数字数组。现在您可以遍历哈希并根据需要处理它。

于 2013-09-18T04:33:46.970 回答