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
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;
}