Perl File Handling
File handling is the most important part in any programming language. A filehandle is an internal Perl structure that associates with a file name.
Perl File handling is important as it is helpful in accessing file such as text files, log files or configuration files.
Perl filehandles are capable of creating, reading, opening and closing a file.
Perl Create File
We are creating a file,
file1.txt
with the help of open() function.
The $fh (file handle) is a scalar variable and we can define it inside or before the open() function. Here we have define it inside the function. The '>' sign means we are opening this file for writing. The
$filename
denotes the path or file location.
Once file is open, use $fh in print statement. The print() function will print the above text in the file.
Now we are closing $fh. Well, closing the file is not required in perl. Your file will be automatically closed when variable goes out of scope.
my $filename = 'file1.txt';
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh "Hello!! We have created this file as an example\n";
close $fh;
print "done\n";
Output:
done.
A file file1.txt will be created in our system.
Perl Open File
We can open a file in following ways:
(<) Syntax
The < sign is used to open an already existing file. It opens the file in read mode.
open FILE, "<", "fileName.txt" or die $!
(>) Syntax
The > sign is used to open and create the file if it doesn't exists. It opens the file in write mode.
open FILE, ">", "fileName.txt" or die $!
The "<" sign will empty the file before opening it. It will clear all your data of that file. To prevent this use (+) sign before ">" or "<" characters.
(+>+<) Syntax
open FILE, "+<", "fileName.txt" or die $!
open FILE, "+>", "fileName.txt" or die $!
(>>) Syntax
The >> sign is used to read and append the file content. It places the file pointer at the end of the file where you can append the information. Here also, to read from this file, you need to put (+) sign before ">>" sign.
open FILE, "<", "fileName.txt" or die $!
Perl Read File
You can read a complete file at once or you can read it one line at a time. We'll show an example for both. Opening a file to read is similar to open a file to write. With only one difference that ">" is used to write and "<" is used to read the file.
We have created a file
file1.txt
with the following content:
This is the First Line.
This is the Second Line.
This is the Third Line.
This is the Fourth Line.
To read Single line at a time
First line of file1.txt will be displayed. Content of $row will be printed with "done" to make it clear that we reached at the end of our program.
use strict;
use warnings;
my $filename = 'file1.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
my $row = <$fh>;
print "$row\n";
print "done\n";
Output:
This is the First Line.
Done.
To read Multi lines at a time
Now we know to read single line from a file. To read multiple lines put $row in a while loop.
Every time, when while loop will reach its condition, it will execute
my $row =
. It will read the next line from the file. At the last line, $fh will return undef which is false and loop will terminate.
use strict;
use warnings;
my $filename = 'file1.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
while (my $row = <$fh>) {
chomp $row;
print "$row\n";
print "done\n";
Output:
This is the First Line.
This is the Second Line.
This is the Third Line.
This is the Fourth Line.
Done.
Perl Write File
Through file writing, we'll append lines in the file1.txt. As already stated, new lines will be added at the last of the file.
open (FILE, ">> file1.txt") || die "problem opening $file1.txt\n";
print FILE "This line is added in the file1.txt\n";
# FILE array of lines is written here
print FILE @lines1;
# Another FILE array of lines is written here
print FILE "A complete new file is created";
# write a second array of lines to the file
print FILE @lines2;
Output:
This line is added in the file1.txt
A complete new file is created
Perl Close File
Perl close file is used to close a file handle using close() function. File closing is not compulsory in perl. Perl automatically closes file once the variable is out of scope.
open FILE1, "file1.txt" or die $!;
close FILE1;
Perl File Handle Operator, <FILEHANDL>
File handle operator is the main method to read information from a file. It is used to get input from user. In scalar context, it returns a single line from the filehandle and in line context, it returns a list of lines from the filehandle.
print "What is your age?\n";
$age = <STDIN>;
if($age >= 18)
print "You are eligible to vote.\n";
} else {
print "You are not eligible to vote.\n";
Output:
1. What is your age?
You are eligible to vote
2. What is your age?
You are not eligible to vote.
Perl File Handle print() function
The print() function prints back the information given through filehandle operators.
print "Welcome to my site\n";
Output:
Welcome to my site
Perl Copying a File
We can copy content of one file into another file as it is. First open file1 then open file2. Copy the content of file 1 to file2 by reading its line through a while loop.
# Opening file1 to read
open(File1Data, "<file1.txt");
# Opening new file to copy content of file1
open(File2Data, ">file2.txt");
# Copying data from file1 to file2.
while(<File1Data>)
print File2Data $_;
close( File1Data );
close( File2Data );
Output:
A new file file2.pl will be created in the location where file1.pl exists.
Perl File Test Operators
There are different test operators to check different information about a file. Some of the test operators are as follows:
Test operators
Description
Return total access time of file since the program started.
Check whether file is block device or not.
Check whether it is a binary file.
Check whether file is character device.
Return inode change time of file since the program started.
Check whether file is a directory.
Check whether file exists or not.
Check type of file whether it is regular, symbolic link or other type of file.
Check whether file have setgid bit set.
Check whether file have sticky bit set.
Check if file is a symbolic link. In dos, it always return false.
Return file modification time in days since the program started.
Check if file is owned by an effective uid, in dos, it always return true.
Check if file is owned by a real uid, in dos, it always return true.
Check whether file is a named pipe.
Check whether file is readable or not.
Check whether file is readable by real uid or not. In dos, it is same as -r.
Return the file size in bytes.
Check if file is a socket.
Check if file is opened to a tty (terminal)
Check if file is a text file.
Check if file has setuid bit set.
Check if file is writable or not.
Check if file is writable by real uid/gid.
Check if file can be executed or not.
Check if file can be executed by real uid/gid.
Check if file size is zero or not.
Perl Using File Test Operators
To test different features within Perl, a series of test operators are present. In the given example, we have tested different features of file1.txt. All the outcomes are merged with join() function.
my $a = "/Users/javatpoint/Desktop/file1.txt";
my (@description, $size);
if (-e $a)
push @description, 'binary' if (-B _);
push @description, 'a socket' if (-S _);
push @description, 'a text file' if (-T _);
push @description, 'a block special file' if (-b _);
push @description, 'a character special file' if (-c _);
push @description, 'a directory' if (-d _);
push @description, 'executable' if (-x _);
push @description, (($size = -s _)) ? "$size bytes" : 'empty';
print "file1.txt is ", join(', ',@description),"\n";
Output:
file1.txt is a text file, 67 bytes
Next Topic
Perl chop() Vs chomp()