如何在perl中每3行读取一次? [英] How to read every 3 lines in perl?
本文介绍了如何在perl中每3行读取一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
抱歉英语不好
我有一个这样的txt文件:
I have a txt file like this:
id: 1
name: a
sex: m
id: 2
name: b
sex: f
所以我想把这个文件的每 3 行读到一个数组中
so I would like to read every 3 lines of this file to an array
[ { id =>1, name => a, sex => m }, { id=>2, name=>b, sex=>f}]
如何在 perl 中每 3 行读取一次?
How to read every 3 lines in perl?
推荐答案
以下内容满足您的要求:
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;
}
还有以下内容:
my @recs;
my $rec;
while (<>) {
chomp;
my ($key, $val) = split(/:\s*/, $_, 2);
if ($. % 3 == 1) {
$rec = {};
push @recs, $rec;
}
$rec->{$key} = $val;
}
但是,我认为最好依赖以 id
键值开头的记录.
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;
}
这篇关于如何在perl中每3行读取一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文