Trí Trương
Trí Trương

Reputation: 31

stdin check word in file with perl

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 should output 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?

Upvotes: 1

Views: 59

Answers (2)

craigb
craigb

Reputation: 1091

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.

Upvotes: 1

Dan Bonachea
Dan Bonachea

Reputation: 2477

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

Upvotes: 0

Related Questions