固定幅はunpack
私に言います。正規表現で解析して分割することは可能ですがunpack
、固定幅のデータに適したツールであるため、より安全な選択である必要があります。
最初のフィールドの幅を12に、その間の空きスペースを13に設定しました。これは、このデータで機能します。あなたはそれを変える必要があるかもしれません。テンプレート"A12A13A*"
は、「12個、次に13個のASCII文字を検索し、その後に任意の長さのASCII文字を検索する」ことを意味します。unpack
これらの一致のリストを返します。また、文字列が指定されていない場合unpack
に使用します。これは、ここで行うことです。$_
サンプルデータにあるように、最初のフィールドがコロンまで固定幅でない場合は、テンプレートのフィールド(たとえば、「A25A *」)をマージしてから、コロンを削除する必要があることに注意してください。
フィールド名が一意かどうかわからないため、ストレージデバイスとしてアレイを選択しました。ハッシュは同じ名前のフィールドを上書きします。配列のもう1つの利点は、ファイルに表示されるデータの順序が保持されることです。これらが無関係で、クイックルックアップが優先される場合は、代わりにハッシュを使用してください。
コード:
use strict;
use warnings;
use Data::Dumper;
my $last_text;
my @array;
while (<DATA>) {
# unpack the fields and strip spaces
my ($field, undef, $text) = unpack "A12A13A*";
if ($field) { # If $field is empty, that means we have a multi-line value
$field =~ s/:$//; # strip the colon
$last_text = [ $field, $text ]; # store data in anonymous array
push @array, $last_text; # and store that array in @array
} else { # multi-line values get added to the previous lines data
$last_text->[1] .= " $text";
}
}
print Dumper \@array;
__DATA__
field name 1: Multiple word value.
field name 2: Multiple word value along
with multiple lines.
field name 3: Another multiple word
and multiple line value
with a third line
出力:
$VAR1 = [
[
'field name 1:',
'Multiple word value.'
],
[
'field name 2:',
'Multiple word value along with multiple lines.'
],
[
'field name 3:',
'Another multiple word and multiple line value with a third line'
]
];