Read a file in Perl

Home > Search
  by

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

 


Read an entire file

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 (<FH>) {
  print $_;
}

close(FH);

 


Display lines that contain a certain string

Let's say file.txt has numerous lines of text.

Hello World
Goodbye Earth
How are you

 

The following script will only print lines that contain the text "Hello".

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

while (<FH>) {
  if ($_ =~ /Hello/) {
  print $_;
  }
}

close(FH);

 

Often, you will want to create a new variable that contains a certain string from the file. It's important to use the .= operator so that each match is appended to the $Greeting variable.

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

while (<FH>) {
  if ($_ =~ /Hello/) {
  $Greeting .= $_;
  }
}

close(FH);

print $Greeting;


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.




Comments