2014-09-19 56 views
0

行我有一個文件的內容:是:從文件中讀取視病情

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 

我想讀「90516」即工作項的使用Perl和放置在數組中的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

顯示你的代碼。 – edem 2014-09-19 10:17:49

回答

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 
+0

如果我想讓該條目在數組中獨一無二,該怎麼辦?應該沒有重複的工作項目。 – user3616128 2014-09-22 07:45:30

+0

[perlfaq4 - 如何從列表或數組中刪除重複元素?](http://perldoc.perl.org/perlfaq4.html#How-can-I-remove-duplicate-elements-from-a-list-或陣列%3f)的 – Miller 2014-09-22 14:52:18