How to read and write files in Perl

Home > Search > How-to
  by

or die $!

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

 


Display file content

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;

 


Writing text to a file

The following markup is used to redirect the text Hello World to file.txt. A single > is used, meaning that the entire file will be overwritten with the text Hello World.

my $file = "/path/to/file.txt";
open(FH, '>', "$file") or die "cannot open $file $! \n";
print FH "Hello World";
close(FH);

 

In this example, text is written to a CSV file. Use \n where you want your data to appear on the next line, and separate data with a comma.

my $file = "/path/to/file.csv";
open(FH, '>', $file) or die "cannot open $file $! \n";
print FH "Column1,Column2,Column3,Column4\n";
print FH "Data,Data,Data,Data\n";
print FH "Data,Data,Data,Data\n";
close(FH);

 


Sum of integers in a file

Let's say file1.txt contains integers.

5
-10
15.4
20

 

The following markup will get the sum of the integers in file1.txt. Running this will script will produce 30.4, which is the sum.

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

my $sum = 0;
while (<FH>) {
  $sum += $_;
}

close(FH);

print "$sum\n";

 


Count  number of lines in a file

$. is the default Perl variable to count the number of lines in a file.

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

my $count = 0;
while (<FH>) {
  $count = $.;
}

close(FH);

print "$count\n";

 


Replace text in a file

Let's say file.txt contains the text "Hello World". The following Perl script will open file.txt, and then replace the text "World" with "Earth".

# Load the content of the file into an array
open(FH, '<', '/path/to/file.txt') or die "cannot open file $! \n";
@array = <FH>;
close(FH);

# Overwrite file.txt with the content of array, while also removing and/or replacing lines
open(FH, '>', '/path/to/file.txt') or die "cannot open file $! \n";
foreach $line (@array) {
  print FH $line unless ($line m/stuff to remove/);
}
close(FH);

 


Read and write to the same file

In this example, "Hello World" is appended to the file.

my $file = "example.txt";

# Open the original file
open(IN, '<', "$file") or die "Cannot open $file $! \n";

# Create a tmp file
open(OUT, '>>', "${file}.tmp") or die "Cannot create $file.tmp $! \n";

# Append something to the top of the tmp file
print OUT "Hello Top\n";

# Copy everything in the original file to the tmp file
while (<IN>) {
  $_ =~ s/old/new/g; # Replace "old" with "new"
  print OUT $_;
}

# Append something to the bottom of the tmp file
print OUT "Hello Bottom\n";

# Close both files
close(IN);
close(OUT);

# Delete the original file
unlink($file);

# Rename the tmp file to have the original file name
rename("${file}.tmp", $file);

 



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