FreeKB - Read a file in Perl
Read a file in Perl

Home > Search

When attempting to open a file in Perl, it's always a good idea to use "or die" and $!. "or die" will display the text following the "or die" statement if the file cannot be opened, and $! will display the reason why the file could not be opened.

open(FH, "<", $file) or die "cannot open $file $! \n";


Following in an example of how to read a file in Perl. This will display every line in file.txt.

my $file = "/path/to/file.txt";
open(FH, "<", $file) or die "cannot open $file $! \n";

while (my $line = <FH>) {
  print $line;

close FH;



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.