,如果你使用的$/
這是容易得多 - 記錄分隔符。並將其設置爲"\n\n"
。
但正如在Dave Cross的評論中指出的那樣 - 最好將其設置爲''
,因爲然後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必須是唯一的才能工作)。
預期產量是多少? –
不只是輸出,但你打算如何使用這些數據,一旦你分開它? –
條目是否總是用空行分隔? – choroba