Regex Perl:将新行转换为逗号,逗号分隔在两个重复单词之间

Regex Perl:将新行转换为逗号,逗号分隔在两个重复单词之间,regex,perl,Regex,Perl,下面是带有重复行的单列的输出,重复行可以是regex/split等的一部分 我想将分组列转换为逗号分隔的格式。有人能帮我吗 之前: An instance of HostInfo 1=? 2=? 3=? 4=? 5=? An instance of HostInfo 1=? 2=? 3=? 4=? 5=? 之后 像这样的东西行吗 use strict; use warnings; undef $/; my $output = <DATA>; my @pa

下面是带有重复行的单列的输出,重复行可以是regex/split等的一部分

我想将分组列转换为逗号分隔的格式。有人能帮我吗

之前:

An instance of HostInfo
1=?  
2=?   
3=?    
4=?  
5=?
An instance of HostInfo
1=?
2=?
3=?
4=?
5=?
之后


像这样的东西行吗

use strict;
use warnings;

undef $/;

my $output = <DATA>;

my @parts = split /An instance of HostInfo/m, $output;

my $ctr = 1;
for my $part (@parts) {
  my @lines = split "\n", $part;
  @lines = grep {$_} @lines;
  next unless @lines;
  s/^\s+//g for @lines;
  s/\s+$//g for @lines;
  print $ctr++, ', ', join(", ", @lines),"\n";
}

__DATA__
An instance of HostInfo
1=?  
2=?   
3=?    
4=?  
5=?
An instance of HostInfo
1=?
2=?
3=?
4=?
5=?
使用严格;
使用警告;
未定义$/;
我的$output=;
my@parts=split/HostInfo/m的实例,$output;
我的$ctr=1;
对于我的$part(@parts){
my@lines=split“\n”,$part;
@lines=grep{$}@lines;
下一步,除非@行;
s/^\s+//g表示@行;
s/\s+$//g表示@行;
打印$ctr++、'、'、join(“、”、@行)、“\n”;
}
__资料__
HostInfo的一个实例
1=?  
2=?   
3=?    
4=?  
5=?
HostInfo的一个实例
1=?
2=?
3=?
4=?
5=?
这会将示例输出读取为单个字符串,并在“HostInfo实例”上拆分它, 然后在每个线段上循环,分割线条,修剪线条,最后将它们重新连接在一起。

尝试这样做:

use strict; use warnings;

my ($count, $hash);

# magic diamond operator to read INPUT
while (<>) {
    # removes newlines
    chomp;
    # if the line contains /An instance/
    # incrementing $count and skipping this line
    do{ $count++; next } if /An instance/;
    # else add current line in a reference to an array
    push @{ $hash->{$count} }, $_;
}

# iterating over "instances"
foreach my $first_level (sort keys %$hash) {
    # finally we print the result by de-referencing the HASH ref
    print "$first_level ", join ", ", @{ $hash->{$first_level} }, "\n";
}
使用严格;使用警告;
我的($count,$hash);
#读取输入的幻方菱形运算符
而(){
#删除换行符
咀嚼;
#如果该行包含/个实例/
#递增$count并跳过此行
do{$count++;next}if/An实例/;
#否则,请在对数组的引用中添加当前行
push@{$hash->{$count},$\;
}
#迭代“实例”
foreach my$first_级别(排序键%$hash){
#最后,我们通过取消引用HASH ref来打印结果
打印“$first_level”,join“,”,@{$hash->{$first_level}},“\n”;
}
用法

perl script.pl < input_file.txt
perlscript.pl
应该记住,Perl中的行处理是记录处理的一个实例。您可以将记录分隔符设置为适合您的数据

假设文件确实包含字符串“一个HostInfo实例”,您可以执行以下操作

您还可以设置记录分隔符:

use English qw<$RS>;
my $old_rs = $RS;
local $RS = "An instance of HostInfo\n";
use English qw<$RS>;
my $old_rs = $RS;
local $RS = "An instance of HostInfo\n";
while ( <$input> ) { 
    chomp; # removes record separator
    next unless $_;
    ...
}
say join( ', ', split $old_rs );