-4

我在解析文本文件的输出时遇到问题。我想在字符之间添加管道符号进行类似于 egrep 的多重搜索,文本文件如下

service entered the stopped state,critical
service entered the running state,clear

代码:

open(my $data, '<', $Config_File) or die "Could not open '$Config_File"
my $reg_exp;
my $severity;
my @fields=();
while (my $line = <$data>) 
{  
   chomp $line;   
   if(!$line =~ /^$/)
   {
   @fields = split "," , $line;
   $reg_exp = $fields[0];
   $severity = $fields[1]; 
   print $reg_exp;
   }
 }

 #print $fields[0];
 #last unless defined $line;

 close($data);

预期产出

service entered the stopped state|service entered the running state
4

1 回答 1

1

你并不遥远,你只需要实际连接字符串。最简单的方法是将其推$fields[0]送到一个数组,然后等到输入完成再打印它。IE:

my @data;
while (my $line = <$data>) {
   next if $line =~ /^$/;            # no need to chomp
   my @fields = split /,/, $line;
   push @data, $fields[0];
}
print join("|", @data), "\n";

我感觉到您正在尝试使用此代码实现其他目标,这就是所谓的XY-problem

于 2013-02-08T09:35:37.037 回答