Writing or Reading a text file (in Perl)

In data analysis, reading and writing a text file is essential as you can not store all your data in your program. Here, we see how can we write a text file, append to that text file and later read that file.

Writing a text file

#!/usr/bin/perl

$filename = 'filename1.txt';
open($h1, '>', $filename) or die "Could not open file '$filename' $!";
print $h1 qq[
This is my first file written by perl
This is the first line
This is the second line
];

close $h1;
print "Finished writing!\n";

Here, we wrote a set of lines in a text file named “filename1.txt”

Screenshot from 2016-10-30 14-51-30.png

Appending a file

#!/usr/bin/perl

$filename = 'filename1.txt';
open($h1, '>>', $filename) or die "Could not open file '$filename' $!";
print $h1 qq[This is the 3rd line
This is the 4th line
];

close $h1;
print "Finished writing!\n";

Here, we append few lines to the previous text file.

Screenshot from 2016-10-30 14-54-06.png

Reading a file

Reading a file is equally essential as writing a file and sometimes even more if we are just visualizing the data.

#!/usr/bin/perl

$filename = 'filename1.txt';
open(my $h1, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";
 
while (my $row = <$h1>) {
  chomp $row;
  print "$row\n";
}

Let us run the above script and see its output:

Screenshot from 2016-10-30 14-58-17.png