jenglee
jenglee

Reputation: 353

Perl: Searching a file

I am creating a perl script that takes in the a file (example ./prog file) I need to parse through the file and search for a string. This is what I thought would work, but it does not seem to work. The file is one work per line containing 50 lines

@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
        }
    }

Upvotes: 1

Views: 208

Answers (1)

Brian Roach
Brian Roach

Reputation: 76888

You're chomping your user input, but not the lines from the file.

They can't match; one ends with \n the other does not. Getting rid of your chomp should solve the problem. (Or, adding a chomp($line) to your loop).

$match = <STDIN>;

or

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

Edit in the hope that the OP notices his mistake from the comments below:

Changing eq to == doesn't "fix" anything; it breaks it. You need to use eq for string comparison. You need to do one of the above to fix your code.

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

Output:

yup

Upvotes: 3

Related Questions