2012-10-17 41 views
-1

我有一個任務來編寫一個Perl文件來打開一個IP地址及其主機名的文本文件,並用一個新行分隔,並將其加載到一個散列中。然後,我應該要求用戶輸入用戶想要在文件中搜索的內容。如果找到結果,程序應打印該值和鍵,並再次要求輸入,直到用戶不輸入任何內容。我甚至沒有接近尾聲,但需要一點指導。我已經將來自這裏的一些代碼和通過使用一些Google-Fu綁定在一起。打開一個文本文件作爲散列並在該散列內搜索

這是我的工作正在進行中:

#!/usr/bin/perl 

print "Welcome to the text searcher! Please enter a filename: "; 

$filename = <>; 

my %texthash =(); 

open DNSTEXT, "$filename" 
    or die! "Insert a valid name! "; 

while (<DNSTEXT>) { 

    chomp; 
    my ($key, $value) = split("\n"); 

    $texthash{$key} .= exists $texthash{$key} 
        ? ",$value" 
        : $value; 
} 
print $texthash{$weather.com} 

#print "What would you like to search for within this file? " 

#$query = <> 

#if(exists $text{$query}) { 

由於可能是有目共睹的,我完全迷失了方向。我不知道我是否正確地將文件插入散列,或者如何打印一個值以進行調試。

+1

'while(){'只讀一行。所以你不能把它分成'\ n'。你需要保存第一行再讀一行,然後把它們放在一起。 –

+0

要打印參考,請使用'Data :: Dumper',例如'使用Data :: Dumper;打印Dumper(\%hash);' –

回答

-1

這裏的問題是我們不知道輸入文件是什麼樣的。假設輸入文件莫名其妙的樣子:

key1,value1 
key2,value2 
key3,value3 

(或其他類似的方式,在這種情況下,密鑰和值對用逗號隔開),你可以這樣做:

my %text_hash; 

# the my $line in the while() means that for every line it reads, 
# store it in $line 
while(my $line = <DNSTEXT>) { 
    chomp $line; 

    # depending on what separates the key and value, you could replace the q{,} 
    # with q{<whatever is between the key and value>} 
    my ($key, $value) = split q{,},$line; 

    $text_hash{$key} = $value; 

} 

但是的,請告訴我們該文件的內容是什麼樣的。

+0

該文件由主機名和IP地址由*換行符*分隔,OP在第1到第2行中指出。此外,split的第一個參數是一個正則表達式,一個字符串。使用'q()'是誤導性的。而是使用'/,/','m(,)'或'qr(,)'。 – amon

+0

對不起。無法捕捉到這一點。我的生活是一個謊言,一直以來我認爲'split'的第一個參數是一個字符串。感謝那。 :) –