2014-01-13 33 views
2

我有兩個數組在我的perl ,我想從其他數組grep一個數組我的代碼在Perl中如下。從Perl中的其他數組grep一個數組

#!/usr/bin/perl 
open (han5, "idstatus.txt"); 
open (han4, "routename.txt"); 
@array3 = <han4>; 
@array4 = <han5>; 
foreach (@array3) { 
@out = grep(/$_/, @array4); 
print @out; } 

文件routename.txt

strvtran 
fake 
globscr 

文件idstatus.txt

strvtran online 
strvtran online 
strvtran online 
globscr online 
globscr online 
globscr online 
globscr online 
globscr online 
Xtech dead 
Xtech dead 
fake online 
fake online 
fake connecting 
walkover123 online 
walkover123 online 

現在我想從idstatus.txt和應該輸出的grep globscr元素如:

globscr online 
globscr online 
globscr online 
globscr online 
globscr online 

我不想使用任何系統命令。請幫我在這裏

回答

2

你不刪除換行符,所以你的匹配包括一個換行符在它正在尋找。

您還需要使for循環使用一個不同的變量,因爲在grep中,$_只會引用當前正在檢查的grep列表中的元素。

嘗試:

chomp(@array3 = <han4>); 
@array4 = <han5>; 
foreach my $routename (@array3) { 
    @out = grep(/$routename/, @array4); 
    print @out; 
} 

這將輸出:

strvtran online 
strvtran online 
strvtran online 
fake online 
fake online 
fake connecting 
globscr online 
globscr online 
globscr online 
globscr online 
globscr online 

我不知道你想從idstatus.txt用grep globscr的意思; routename.txt扮演什麼角色?

+0

文件idstatus具有多個元素,並且一些元素存在於routename中。例如。在idstatus.txt中有一個元素「strvtran online」,而routename.txt中的元素是「strvtran」。所以我想從idstatus.txt grep「strvtran」並獲得像「strvtran online」這樣的idstatus.txt元素......我已經使用了你的腳本,但它沒有顯示任何東西...... – user2916639

+0

然後你沒有使用我的腳本或你的文件不是你說的?準確顯示您運行的內容(編輯您的問題) – ysth

2

而不是grep平每行,可以考慮建立一個包含路徑名稱爲交替正則表達式:在你的數據集

use strict; 
use warnings; 
use autodie; 

open my $rnameFH, '<', 'routename.txt'; 
chomp(my @routename = <$rnameFH>); 
close $rnameFH; 

my $names = '(?:' . (join '|', map { "\Q$_\E" } @routename) . ')'; 
my $regex = qr /^$names/; 

open my $idFH, '<', 'idstatus.txt'; 

while(<$idFH>){ 
    print if /$regex/; 
} 

close $idFH; 

輸出:

strvtran online 
strvtran online 
strvtran online 
globscr online 
globscr online 
globscr online 
globscr online 
globscr online 
fake online 
fake online 
fake connecting 

的腳本創建一個或類型的正則表達式,通過join將路由名稱用「|」 (打印$names看到這個)。 map只能引用可能在名稱中的任何元字符,例如.*^等,因爲這些會影響匹配。

希望這會有所幫助!

相關問題