我试图解析看起来像这样的文本文件:
aaa aaa aaa
111 111 111
bbb bbb bbb
222 222 222
ccc ccc ccc
333 555 666
ddd ddd ddd
444 444 444
为了得到这样的结果:
aaa aaa111 aaa
bbb bbb222 bbb
ccc ccc333 ccc
ddd ddd444 ddd
我的代码如下所示:
use strict;
use warnings;
use Data::Dumper;
my @array;
my $flag = "";
my $permit;
my $adrr;
my $descr;
my $str_no;
my $file = 'Permit.txt';
open my $fh, '+<', $file
or die "Cannot open 'file ' for writing: $!";
while (my $line = <$fh>) {
chomp($line);
if ($line =~ /^[abcd]/) {
$str_no = substr($flag,0,3);
$permit = substr($line, 0, 3);
$adrr = substr($line, 4, 3);
$descr = substr($line, 8, 3);
if($flag) {
if ($str_no) {
$adrr .= $str_no;
}
}
push @array, {permi => $permit, adr => $adrr, desc => $descr};
$flag = "";
} else {
$flag = $line;
}
}
print Dumper(\@array);
但是这会将我的所有值从数字行中推下来,将第一个数字连接到第二个字母行。
答案 0 :(得分:5)
一次读取两行文件:
use strict;
use warnings;
while (<DATA>) {
my @fields = split;
my @numbers = split(' ', <DATA>);
$fields[1] .= $numbers[0];
print "@fields\n";
}
__DATA__
aaa aaa aaa
111 111 111
bbb bbb bbb
222 222 222
ccc ccc ccc
333 555 666
ddd ddd ddd
444 444 444
输出:
aaa aaa111 aaa
bbb bbb222 bbb
ccc ccc333 ccc
ddd ddd444 ddd