我有一個檔案 aa.txt:
Nothing is worth more than the truth.
I like to say hello to him.
Give me peach or give me liberty.
Please say hello to strangers.
I'ts ok to say Hello to strangers.
我嘗試了代碼:
use strict;
use warnings;
my $input_aa='aa.txt';
while (1){
print "Enter the word you are looking for (or 'quit' to exit): ";
my $answer = <STDIN>;
chomp $answer;
last if $answer =~/quit/i; #
print "Looking for '$answer'\n";
my $found = 0;
open my $f, "<", $input_aa or die "ERROR: Cannot open '$input_aa': $!";
while (<$f>) {
m/$answer/ or next;
$found=1;
last;
}
close $f;
if ($found){
print "Found $answer!\n";
while ( my $line = <$input_aa> ) {
print $line;
}
}
else{
print "Sorry - $answer was not found\n";
}
}
我希望當我從鍵盤輸入關鍵字時在檔案中進行比較并輸出帶有該單詞的行。例如,當我輸入單詞“Nothing”時,它會輸出“Nothing is worth more than the truth.”這一行。我嘗試了代碼,但是當我從鑰匙串輸入關鍵字時它不輸出該行。問題出在哪里?
uj5u.com熱心網友回復:
您的代碼可以正常作業,直到您嘗試列印匹配的行。您的代碼嘗試讀取<$input_aa>哪個不是有效的檔案句柄。
$found相反,您可以在使用變數找到匹配行時簡單地保存它,例如:
use strict;
use warnings;
my $input_aa='aa.txt';
while (1) {
print "Enter the word you are looking for (or 'quit' to exit): ";
my $answer = <STDIN>;
chomp $answer;
last if $answer =~/quit/i; #
print "Looking for '$answer'\n";
my $found;
open my $f, "<", $input_aa or die "ERROR: Cannot open '$input_aa': $!";
while (<$f>) {
m/$answer/ or next;
$found=$_;
last;
}
close $f;
if (defined($found)) {
print "Found $answer! in this line: $found";
} else {
print "Sorry - $answer was not found\n";
}
}
更改不會初始化$found,因此檢查是否$found已定義。然后我們只列印$found它是否已定義。
uj5u.com熱心網友回復:
看起來問題是這一行:
while ( my $line = <$input_aa> )
嘗試在找到該行時早點保存它,例如替換$found = 1為:
$found = $_;
然后你就可以列印了$found
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/523733.html
標籤:linuxperl
上一篇:bash中基于過濾器的索引陣列
下一篇:更改矩陣檔案的結構
