Take the 2-minute tour ×

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";
share|improve this question
Is it possible the string spans two lines? –  chovy Oct 26 '11 at 3:02
add comment

1 Answer

up vote 3 down vote accepted

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


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

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);



share|improve this answer
So go without the chomp on the user input and chomp @array. I thought that the <> operator reads in the file and does all of the n\ –  jenglee Oct 26 '11 at 2:57
Either chomp both or neither. @array = < >; does not remove newlines. –  Brian Roach Oct 26 '11 at 2:59
So I add the chomp to my loop $match eq chomp($line). But when I run it it does not seem to run the if( $match eq chomp($line)) –  jenglee Oct 26 '11 at 3:05
Thank you so much I solved it by changing eq to == –  jenglee Oct 26 '11 at 3:06
@jenglee - no, you didn't. Using == is incorrect and you will find that things that shouldn't match suddenly do. See my edit to my answer. –  Brian Roach Oct 26 '11 at 3:16
show 3 more comments

Your Answer


