2016-05-12 119 views
0

我已經嘗試了所有步驟,以便將與一個文件相比唯一存在的單詞列表與另一個文件進行比較。我在代碼中進行了一些調試打印,以確定它發生的位置,並發現代碼在比較循環中從不執行任何操作。比較兩個單詞列表並保存不在第二個列表中的單詞perl

我想我是盲目的或忽略了一些非常明顯的東西 - 有人請指出什麼是錯的,並且喜歡嘲笑我的「可能是新手」的錯誤。

while (<IN>) { #read the file 

    chomp; 

    $_ = lc; #convert to lower case 
    s/ --//g; #remove double hyphen dashes 
    s/ -//g; #remove single hyphen dashes 
    s/ +/ /g; #replace multiple spaces with one space 
    s/[~`@#$%^&*-+=<>.,:;?"!_()\[\]]//g; #remove punctuation 

    @hwords = split; 
# foreach $w (@hwords) { print "$w \n";} 

} 
while (<IN0>) { #read the file 

    chomp; 

    $_ = lc; #convert to lower case 
    s/ --//g; #remove double hyphen dashes 
    s/ -//g; #remove single hyphen dashes 
    s/ +/ /g; #replacxew multiple spaces with one space 
    s/[~`@#$%^&*-+=<>.,:;?"!_()\[\]]//g; #remove punctuation 

    @awords = split; 
# foreach $w (@awords) {print "$w\n";} 

} 

$count =0; 

@unique =(); 

print "got here!\n"; # YES - it gets here 

foreach $w (@hwords) { print "$w \n";} 

foreach $h (@hwords) { 

    $x=1; 
    print "got there!\n"; # NOPE, doesn't get here 
    foreach $a (@awords) { 
    if ($h eq $a) { 
     $x=0; 
     print "equals\n"; # NEVER see this 
    } 
    } 
    if ($x eq 1) { 
    ++$count; 
    @unique = @unique, $h; 
    print "$count, $h\n"; # NEVER see this, either 
    } 
} 
+0

需要注意的是正確,你需要用4個空格縮進在編輯器窗口中顯示的代碼。我爲你編輯了這一個 – stevieb

+0

我會推薦'perltidy',以便讓縮進一致。 – Sobrique

回答

1

首先,循環的每次迭代完全替換@hwords@awords。因此,最後,@hwords@awords將只包含來自每個相應文件的最後一行的單詞。

無論如何,你只需要從第一個文件中提取單詞。然後,在讀取第二個文件的同時,將它的單詞與第一個文件中存儲的單詞進行比較。

因此,在第一循環中,而不是設置@hwords,使其成爲查找散:

$hwords{$_} = 1 for split; 

現在,第一個文件讀入之後,其所有的話都是%hwords哈希鍵。

然後,讀取第二文件時,在第二循環中,查找每個單詞在查找散:

print "Word not found: $_\n" 
    for grep { !$hwords{$_} } split; 
1

這是一個常見問題,該解決方案可以在FAQ中找到。

perldoc -q intersect

我要感謝@Botje上#perl irc.freenode.net上提醒我這一點。

0

請檢查:

use Array::Utils qw(:all); 

my @a = qw(a b c d); 
my @b = qw(c d e f); 

#get items from array First list that are not in array Second List 
my @notinsecond = array_minus(@b, @a); 

#get items from array Second list that are not in array First List 
my @notinfirst = array_minus(@a, @b); 


print join "\n", @notinfirst; 
print join "\n", @notinsecond; 
相關問題