Home > Back-end >  stdin check word in file with perl
stdin check word in file with perl

Time:10-30

I have a file 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.

I tried with code:

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";
    }
           }


I want when I enter a keyword from the keyboard to compare in the file and output the line with that word. For example, when I enter the word "Nothing", it outputs the line "Nothing is worth more than the truth.". I tried with the code but it doesn't output the line when i enter the keyword from the keychain. Where's the problem?

CodePudding user response:

Looks like the problem is this line:

while ( my $line = <$input_aa> ) 

Try instead saving away the line earlier when you find it, eg replace $found = 1 with:

$found = $_;

and then later you can just print $found

CodePudding user response:

Your code works correctly, until you try to print the matching line. Your code tries to read <$input_aa> which is not a valid file handle.

Instead, you could simply save the matching line when you find it using the $found variable, eg:

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";
    }
}

The changes are to not initialize $found, so the check is whether $found is defined or not. Then we just print $found if it is defined.

  • Related