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”
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.
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: