我有一个代码用于读取文件,如果某个关键字匹配,则删除一行代码。如果我看到关键词THERMST,我会删除前一行和所有行,直到我到达& :
QNODE "CExtHrn - Heater_Bidon" 1.0 T884 TOTAL
THERMST "CExtHrn" 0 2.500000E+01 3.000000E+01 883 ID 0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 "Heater_Bidon"
NAME2 Heater_ CExtHrn - Heater_Bidon
NAME Heater_ 40097 40170 1
TABTYPE 884 TABLE OPERATION
TABDATA 884 885 INTERP
TABDATA 884 883 THERMST
TABTYPE 885 QNODE TIME
TABDATA 885 2.000000E+01 0.000000E+00
$
但是,由于一个不明原因,当我打印到一个新文件时,它会在某一行上给出几个空字符。奇怪的是,这条线与我刚改变的线无关。如果我不修改文件,通过评论以下行,我不会得到任何空字符。
# We delete the last 2 line and skip the rest of the qnode/thermst definition
splice @INPF1_OUT, -2;
# Skipping the lines until next comment line.
$ii++ until substr($INPF1_IN[$ii], 0, 1) eq '$';
$ii = $ii - 1;
知道这可能是什么?空字符导致我对文件的处理出现问题。
以下是该行:
NAME winte_T 101269 101270 1
这是它在新文件中打印的内容:
NAME winte_T ULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNUL 101269 101270 1
您可以看到导致错误的行与应修改的行无关
谢谢,代码在下面
#!/bin/perl
use strict;
use Text::ParseWords;
open (INPF1_in, '<', $INPF1)
or die "Not able to open : $INPF1";
my @INPF1_IN = <INPF1_in>;
close INPF1_in;
my @INPF1_OUT; # Output INPF1
my $cardno = 1;
my $ii = 0;
until ($ii > $#INPF1_IN) {
my $INPF_line = $INPF1_IN[$ii];
push(@INPF1_OUT, $INPF_line); # Adding line
chomp($INPF_line);
if ($INPF_line eq "-1") {
$cardno++;
}
if ($cardno == 9) {
my @line = parse_line(" ", 0, $INPF_line); # parsing the line elements
if ($line[0] eq "THERMST") { # If Thermostat
# We delete the last 2 line and skip the rest of the qnode/thermst definition
splice @INPF1_OUT, -2;
$ii++ until substr($INPF1_IN[$ii], 0, 1) eq '$';
$ii = $ii-1; # Skipping the lines until next comment line.
}
}
$ii++;
}
open (INPF1_out, '>', $INPF1);
print INPF1_out $_ foreach @INPF1_OUT;
close INPF1_out;
答案 0 :(得分:1)
我可能会误读你的代码,但它看起来就像你在perl中尝试做一些非常简单的事情一样,非常困难。
如果我正确阅读,你要做的是采用输入记录格式,并有条件地打印某些行。 Perl有一个非常好的工具,称为“范围运算符”。
我认为你能用一些相当简单的东西来完成你想要的东西。
#!/bin/perl
use strict;
use warnings;
while ( <DATA> ) {
print unless ( m/^THERMST/ ... m/^\$$/ );
}
__DATA__
QNODE "CExtHrn - Heater_Bidon" 1.0 T884 TOTAL
THERMST "CExtHrn" 0 2.500000E+01 3.000000E+01 883 ID 0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 "Heater_Bidon"
NAME2 Heater_ CExtHrn - Heater_Bidon
NAME Heater_ 40097 40170 1
TABTYPE 884 TABLE OPERATION
TABDATA 884 885 INTERP
TABDATA 884 883 THERMST
TABTYPE 885 QNODE TIME
TABDATA 885 2.000000E+01 0.000000E+00
$
这是一个例子,根据您目前为止提供的数据 - 如果您可以提供更多信息来准确显示您要完成的内容,我将非常确定您可以提取所需的信息而无需必须迭代单词数组中的元素。 Perl可以做得更好。
(我猜有点,因为我们完全不清楚你从哪里获得$cardno
。但是这应该很容易修改以满足你的需要)