如何使用perl基于条件将行拆分为数组?

时间:2013-05-16 02:27:02

标签: perl

如何使用perl基于条件将行拆分为数组?

我有以下文件,每个段落之间有空格分隔符。

logInformation.txt

               LogA
                    fjlfjdklafjdkla;fdjklafdja
                    adjalfdlafdjkla;fdla;fdl;a
                    faklfdaldflkafdlkafdklafdl
              LogB
                    djfkalfjdklafdkla;fdkla;fd
                    afdjkalfdkla;fdlk;afdla;fd
              LogC
                    djfkalfjdklafdkla;fdkla;fd
                    afdjkalfdkla;fdlk;afdla;fd


               LogA
                    fjlfjdklafjdkla;fdjklafdja
                    adjalfdlafdjkla;fdla;fdl;a
                    faklfdaldflkafdlkafdklafdl
              LogB
                    djfkalfjdklafdkla;fdkla;fd
                    afdjkalfdkla;fdlk;afdla;fd
              LogC
                    djfkalfjdklafdkla;fdkla;fd
                    afdjkalfdkla;fdlk;afdla;fd


               LogA
                    fjlfjdklafjdkla;fdjklafdja
                    adjalfdlafdjkla;fdla;fdl;a
                    faklfdaldflkafdlkafdklafdl
              LogB
                    djfkalfjdklafdkla;fdkla;fd
                    afdjkalfdkla;fdlk;afdla;fd
              LogC
                    djfkalfjdklafdkla;fdkla;fd
                    afdjkalfdkla;fdlk;afdla;fd

使用perl,我如何只获取LogB信息

1 个答案:

答案 0 :(得分:1)

my $LogB = 0;
while (<>) {
    $LogB = 1 if /^\s*LogB\b/;        # set flag if line is LogB
    $LogB = 0 if /^\s*Log[^B]\b/;     # clear flag if some other log starts here
    print $_ if $LogB;                # print out LogB, and its entries
}

创建一个列表,同时修剪前导空格并删除LogB s:

my ($LogB, @data);
while (<>) {chomp;
    $LogB = 1 if /^\s*LogB\b/;
    $LogB = 0 if /^\s*Log[^B]\b/;
    $_ =~ s/^\s*(?:\bLogB\b)?\s*//;
    push(@data, $_) if $LogB and $_; 
}
print join("\n", @data), "\n";