How to read every 3 lines in perl?

后端 未结 1 1081
暗喜
暗喜 2021-01-24 23:16

Sorry for the bad English

I have a txt file like this:

id: 1
name: a
sex: m
id: 2
name: b
sex: f

so I would like to read every 3 lines

相关标签:
1条回答
  • 2021-01-25 00:10

    The following does what you ask:

    my @recs;
    while (!eof()) {
       my %rec;
       for (1..3) {
          chomp( my $line = <> );
          my ($key, $val) = split(/:\s*/, $line, 2);
          $rec{$key} = $val;
       }
    
       push @recs, \%rec;
    }
    

    And so does the following:

    my @recs;
    my $rec;
    while (<>) {
       chomp;
       my ($key, $val) = split(/:\s*/, $_, 2);
       if ($. % 3 == 1) {
          $rec = {};
          push @recs, $rec;
       }
    
       $rec->{$key} = $val;
    }
    

    However, I think it would be best to rely on records starting with the id key-value.

    my @recs;
    my $rec;
    while (<>) {
       chomp;
       my ($key, $val) = split(/:\s*/, $_, 2)
       if ($key eq 'id') {
          $rec = {};
          push @recs, $rec;
       }
    
       $rec->{$key} = $val;
    }
    
    0 讨论(0)
提交回复
热议问题