如果您使用$/ - 记录分隔符,这会容易得多。并将其设置为"\n\n"。
但正如 Dave Cross 在 cmets 中所指出的那样 - 将其设置为 '' 可能会更好,因为这样 perl 将跳过多个空白行,否则会获得相同的结果。
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
#set record separator to (one or more) blank lines
local $/ = '';
#iterate each chunk of data
while ( <DATA> ) {
#g matches repeatedly, and so this'll get alternating values
#this conveniently is what you need to assign straight to a hash
my %record = m/(\w+): (.*)/g;
print Dumper \%record;
}
__DATA__
ID: ID_A
attr1: attribute
attr2: name
attr3: city
ID: ID_B
attr1: attribute2
attr2: name2
attr3: city3
attr4: country
提取记录/字段后,您可以将它们推送到记录数组中:
push ( @all_records, \%record );
给予:
$VAR1 = [
{
'attr2' => 'name',
'ID' => 'ID_A',
'attr1' => 'attribute',
'attr3' => 'city'
},
{
'attr2' => 'name2',
'ID' => 'ID_B',
'attr4' => 'country',
'attr1' => 'attribute2',
'attr3' => 'city3'
}
];
或者把它放到一个散列中,键入 ID 号:
$all_records{$record{ID}} = \%record;
给予:
$VAR1 = {
'ID_A' => {
'ID' => 'ID_A',
'attr3' => 'city',
'attr1' => 'attribute',
'attr2' => 'name'
},
'ID_B' => {
'attr2' => 'name2',
'attr3' => 'city3',
'attr1' => 'attribute2',
'attr4' => 'country',
'ID' => 'ID_B'
}
};
取决于您对记录所做的工作 - 如果您只是在处理和丢弃它们,您可能根本不需要“保留”它们,并且如果您有重复的 ID,那么您可能不需要想要使用散列方法的散列(ID 必须是唯一的才能工作)。