Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hello , I have a flat file in which I have words like this.
TEXAS,apple,2,E,0,0000, 0030, 0145, 0030, 0145, 0100, + 0030, 0145, 0000, 0000, 3 NEVADA,GRAPE,2,E,0,0000, 0030, 0145, 0030, 0145, 0100, + 0030, 0145, 0000, 0000, 3 MONTANA,PEAR,2,E,0,0000, 0030, 0145, 0030, 0145, 0100, + 0030, 0145, 0000, 0000, 3
I want to isolate the line containing apple. But when I uses the following code to print the line containing apple.
$fruit = "apple"; if ( $_ =~ /$fruit/) { print "$_"; }
But instead of only printing the line containing 'apple'. It prints out the entire file. How do I make it print only the line containing apple. - Thanku

Replies are listed 'Best First'.
Re: print line containing string
by toolic (Bishop) on May 05, 2010 at 16:39 UTC
    You didn't show how you set $_. The following works as expected for me. It only prints the apple line:
    use strict; use warnings; my $fruit = "apple"; while (<DATA>) { if ( $_ =~ /$fruit/) { print "$_"; } } __DATA__ TEXAS,apple,2,E,0,0000, 0030, 0145, 0030, 0145, 0100, + 0030, 0145, 0000, 0000, 3 NEVADA,GRAPE,2,E,0,0000, 0030, 0145, 0030, 0145, 0100, + 0030, 0145, 0000, 0000, 3 MONTANA,PEAR,2,E,0,0000, 0030, 0145, 0030, 0145, 0100, + 0030, 0145, 0000, 0000, 3
Re: print line containing string
by moritz (Cardinal) on May 05, 2010 at 16:36 UTC
    How do I make it print only the line containing apple

    By making $_ containing only one line at a time.

    Perl 6 - links to (nearly) everything that is Perl 6.
Re: print line containing string
by ChiefAl (Initiate) on May 05, 2010 at 16:59 UTC

    It sounds like you are "slurping" the whole file at once. Check the value of $/ (input record separator) when you read in your file.

      how do I check the $/ (input record saperator)
        Thank you . The input record saperator advice worked . You are an experienced person. Thank you kindly