How to Work With Files in Perl

How to Work With Files in Perl


File I/O in Perl can be approached in a few different manners. Only one method will be introduced, for opening, reading, and writing to files.


An environment with a Perl interpreter. This may be available by default on Linux-based systems, but Windows systems may need Perl to be installed. For Windows, a Perl environment can be set up with installations such as Active State Perl.


With the Perl interpreter set up, open a text file and save it as a “.pl” file. At the top of the file, type:

use strict;
use warnings;
my $logFile = “C:\Users\user\Desktop\filename.txt”;

This will set up your file to be interpreted from the “#!\usr\bin\Perl” executable on Linux, and should be ignored whether it is present or not on a Windows system with a distribution like Active State Perl. It will also create a variable with the path and a filename named “logFile”. Next, you may define a routine as follows:

##comment to name and mark the start of the following openLog subroutine
sub openLog{
open (my $LOG, ‘<’, $logFile) or die “Cannot open file: $! \n\n”;
return $LOG;
}#end openLog

The subroutine opens a filehandle for the ‘$logFile’ file. You can change the ‘<’ to be ‘>’ to open the file for writing instead. The ‘$!’ will display an error message if the operation fails. The two ‘\n’ afterwards are linebreak or newline characters which will display two blank lines after the message is displayed. The declared ‘$LOG’ variable will store the opened file into a ‘filehandle’ called ‘$LOG’. This can be used for manipulating the file line by line.

After the ‘openLog’ subroutine you can add:

while (<$LOG>){
print $_;

This will print each line in the ‘$LOG’ filehandle using the special variable ‘$_’. For writing to files you can use:

print $LOG “text to write to file.\n”;
close $LOG;