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

I am trying to write a program to print all matching lines of a pattern

#!/usr/bin/perl; use warnings; use strict; my $filename = 'C:\Perl\example.txt'; open (my $fh, '<' ,$filename) or die "ERROR: could not open $filename: + $!"; while (<>) { if (/fred/) { print ; } } close ($fh);

Replies are listed 'Best First'.
Re: My program hangs
by Corion (Patriarch) on Jun 23, 2014 at 08:16 UTC

    You are reading from the wrong filehandle:

    open (my $fh, '<' ,$filename) or die "ERROR: could not open $filename: + $!"; while (<>) {

    Instead of reading from standard input (or the file passed on the command line), you want to read from the filehandle you just opened, $fh:

    while (<$fh>) {
Re: My program hangs
by vinoth.ree (Monsignor) on Jun 23, 2014 at 10:10 UTC

    Hi,

    Your program is not hangs,Its waiting for input from you, when you write <> it is a abbrivation for <STDIN>, so it will read either from a file specified on the command line or from stdin if no file is given.

    As told by Corion, you need to use <$fh>, to read from your file handle.


    All is well
Re: My program hangs
by 1s44c (Scribe) on Jun 23, 2014 at 13:13 UTC
    Like Corion says you are reading from the wrong filehandle. But:
    #!/usr/bin/perl;
    You're on unix.
    my $filename = 'C:\Perl\example.txt';
    You're on windows. I'm confused, they can't be both right?

      Windows does not care for the hashbang line of a script. Perl does care for the line, respectively, for the switches on that line.

      In that sense, they can both be right.