使用perl将字符替换为文本文件中的其他字符

时间:2013-02-08 08:22:40

标签: linux perl

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

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

1 个答案:

答案 0 :(得分:1)

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

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

相关问题