2011-10-26 112 views
1

我正在創建一個接收文件的perl腳本(例如./prog文件) 我需要解析文件並搜索字符串。這是我認爲會起作用的,但似乎並不奏效。該文件是每行一行,包含50行Perl:搜索文件

@array = < >; 
    print "Enter the word you what to match\n"; 
    chomp($match = <STDIN>);   

    foreach $line (@array){ 
     if($match eq $line){ 
      print "The word is a match"; 
      exit 
     } 
    } 
+0

是否有可能字符串跨越兩行呢? – chovy

回答

3

您正在扼殺您的用戶輸入,而不是文件中的行。

它們不能匹配;一方以\n結束,另一方不。擺脫chomp應解決問題。 (或者,將chomp($line)添加到您的循環中)。

$match = <STDIN>; 

foreach $line (@array){ 
    chomp($line); 
    if($match eq $line){ 
     print "The word is a match"; 
     exit; 
    } 
} 

編輯在希望OP注意到他從下面的評論中錯誤:

更改eq==不 「修正」 任何東西;它打破了它。您需要使用eq進行字符串比較。您需要執行上述任一操作來修復您的代碼。

$a = "foo\n"; 
$b = "bar"; 
print "yup\n" if ($a == $b); 

輸出:

+0

因此,如果沒有用戶輸入和chomp @array chomp。我認爲<>操作符讀入文件並且執行所有的n \ – jenglee

+0

既可以是chomp也可以不是。 '@array = < >;'不*刪除換行符。 –

+0

所以我添加chomp到我的循環$ match eq chomp($ line)。但是當我運行它似乎並沒有運行if($ match eq chomp($ line)) – jenglee