是:根据条件从文件中读取行

时间:2014-09-19 10:06:37

标签: perl

我的文件内容为:

Change sets:
  (0345) ---$User1 "test12"
    Component: (0465) "textfiles1"
    Modified: 14-Sep-2014 02:17 PM
    Changes:
      ---c- (0574) /<unresolved>/sha.txt
    Work items:
      (0466) 90516 "test defect

我想阅读&#34; 90516&#34;即使用perl的工作项的id并将其放在一个数组中。 注意:这是一个条目,文件中可以有多行这样的行。 我想捕获所有这样的工作项ID,并在perl中放置一个数组。 代码

$file = new IO::File;
$file->open("<sha.log") or die "Cannot open sha.log";
@file_list = <$file>;
$file->close;
my %seen;
foreach $line (@file_list) {
    #clear the array
    undef %seen;
    while ( $line =~ m/Work items:/g ) {
        @temp = split( /[:|,]/, $1 );
        #push the item to array only if no items in temp array i.e. if the occurance is for the first time
        next if $seen{ $temp[0] }++;
        push @work_items, $temp[0];
    }
}

1 个答案:

答案 0 :(得分:0)

使用Range operator ..

use strict;
use warnings;
use autodie;

#open my $fh, '<', 'sha.log';
my $fh = \*DATA;

my @work_items;

while (<$fh>) {
    if ( my $range = /Work items:/ ... !/^\s*\(\d+\) (\d+)/ ) {
        push @work_items, $1 if $range > 1 && $range !~ /E/;
    }
}

print "@work_items\n";

__DATA__
Change sets:
  (0345) ---$User1 "test12"
    Component: (0465) "textfiles1"
    Modified: 14-Sep-2014 02:17 PM
    Changes:
      ---c- (0574) /<unresolved>/sha.txt
    Work items:
      (0466) 90516 "test defect
      (0467) 90517 "test defect
Change sets:
  (0345) ---$User1 "test12"
    Component: (0465) "textfiles1"
    Modified: 14-Sep-2014 02:17 PM
    Changes:
      ---c- (0574) /<unresolved>/sha.txt
    Work items:
      (0468) 90518 "test defect

输出:

90516 90517 90518