我有这样的数据:
Re: Building A
Month
kWh
1
100
2
110
3
105
Re: Building B
Month
kWh
1
200
2
210
3
205
我想将它转换为多个文本文件,每个文件对应一个建筑物。我的计划是:
- 提取建筑物分隔线之间的值
- 将行转换成表格
对于任务 (1),我尝试像这样使用触发器运算符:
while( <DATA> ) {
next unless /^Re: Building A/ .. /^Re: Building B/;
my $line = $_;
print $line;
}
但它不起作用,因为上面将仅显示建筑物 A 的数据。数据是针对多个建筑物(大约 50 个),因此我需要以递归方式执行此操作。我还没有开始做任务(2)。
我们将不胜感激。
请您参考如下方法:
我会做这样的事情:
#!/usr/bin/perl
use strict;
use warnings;
my %buildings;
while (<DATA>) {
chomp;
$buildings{$1} = [] if /^Re: Building ([AB])/;
push @{$buildings{$1}}, $_ if $_;
}
while (my ($building, $data) = each %buildings) {
open(my $out, '>', "$building.txt") or die "Unable to open file for writing: $!\n";
for my $i (1 .. $#$data / 2) {
print $out sprintf "%s\t%s\n", $data->[$i*2-1], $data->[$i*2];
}
close $out;
}
A.txt:
Month kWh
1 100
2 110
3 105
B.txt:
Month kWh
1 200
2 210
3 205
