Search code examples
perl

How can I read input from a text file in Perl?


I would like to take input from a text file in Perl. Though lot of info are available over the net, it is still very confusing as to how to do this simple task of printing every line of text file. So how to do it? I am new to Perl, thus the confusion .


Solution

  • First, open the file:

    open my $fh, '<', "filename" or die $!;
    

    Next, use the while loop to read until EOF:

    while (<$fh>) {
        # line contents's automatically stored in the $_ variable
    }
    close $fh or die $!;