我有一个文件可供阅读,如下所示。我需要从read.txt读取数据并写入另一个文件write.txt,如图所示。 read.txt中有很多其他值以类似的方式。我需要将它们写入write.txt。请帮忙。
read.txt
value: length
var: cm
data: 10
value: weight
var: lb
data: 145
value:currency
var: dollar
data: 1000
write.txt
#Header Info, length_cm, weight_lb, currency_dollar
#data, 10, 145, 1000
答案 0 :(得分:2)
请参阅$/
my @attr_names;
my %rec;
local $/ = '';
while (<>) {
my %attr;
while (/^([^:]+):\s*(.*)/mg) {
$attr{$1} = $2;
}
warn("Missing value"), next if !$attr{value};
warn("Missing var"), next if !$attr{var};
warn("Missing data"), next if !$attr{data};
my $attr_name = "$attr{value}_$attr{var}";
push @attr_names, $attr_name;
$rec{$attr_name} = $attr{data};
}
print(join(',', @rec{@attr_names}), "\n");