2015-06-04 26 views
0

我需要幫助拿出,作爲 SORT命令執行相同功能的工作perl腳本:sort –t’;’ –k1,1 File1.txt File2.txt File2.txt | uniq –u比較數據,並打印出獨特的發現

我有兩個文件由分號分隔。我需要僅基於第一列(數字)fror File2.txt(差異而非)的唯一性提取出唯一行,其他列2和列3在此期間不相關。

FILE1.TXT(主文件)

123;winter;season 
456;fall;season 
789;autumn;season 
321;summer;season 
654;dry;weather 
987;cold;weather 

FILE2.TXT

123;winter;season 
456;fall;season 
789;autumn;season 
321;summer;season 
369;march;month 
147;september;month 

預期輸出(369 & 147不在FILE1.TXT)

369;march;month 
147;september;month 

迄今我寫了,但它打印出兩個文件;

#!/usr/bin/perl 

# create names lookup table from first file 
open(DATA, "<File1.txt") or die "Couldn't open file File1.txt, $!"; 
my %names; 
while (<DATA>) { 
    (my @data)= split /;/, $_; 
    $names{$data} = 1; 
    last if eof; 
} 

# scan second file 
open(DATA2, "<File2.txt") or die "Couldn't open file File2.txt, $!"; 
while (<DATA2>) { 

    print if /^(\d+)/ && not $data[0]; 
    } 
} 

我仍然很難理解數組和哈希值。任何幫助改善我的代碼將不勝感激。請添加評論或指出我有任何錯誤...提前致謝。,

回答

0

你不遠處。

  • 在你把分號分隔的字段在陣列@data第一環路,然後寫

    $names{$data} = 1; 
    

    $data是完全單獨的變量,並且在該點是未定義的。你想

    $names{$data[0]} = 1; 
    

    它使用您測試$data[0]不再存在,因爲你宣佈@data上循環內的@data陣列

  • 在第二循環的第一要素。因爲你的正則表達式捕捉你可以說

    print if /^(\d+)/ and not $names{$1}; 
    

    $1第一場,你的計劃將努力

這也是必不可少use strictuse warnings在每一個Perl的頂部程序。該措施會產生一些警告信息,幫助您解決上述錯誤。您還應該使用詞法文件句柄和open的三參數表單。而且你的last if eof這條線是不必要的,因爲while條件無論如何都會退出循環。

下面是應用了這些修補程序的重寫

#!/usr/bin/perl 

use strict; 
use warnings; 

open my $f1_fh, '<', 'File1.txt' or die "Couldn't open file File1.txt: $!"; 
my %names; 
while (<$f1_fh>) { 
    my @data = split /;/, $_; 
    $names{$data[0]} = 1; 
} 

open my $f2_fh, '<', 'File2.txt' or die "Couldn't open file File2.txt: $!"; 
while (<$f2_fh>) { 
    print if /^(\d+)/ and not $names{$1}; 
} 

輸出

369;march;month 
147;september;month