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.

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.

Example
snippet
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.

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.

snippet
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.

snippet
open FILE, ">", "fileName.txt" or die $!
(+>+<) Syntax
snippet
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.

snippet
open FILE, "<", "fileName.txt" or die $!

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:

Example
snippet
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.

Example
snippet
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 = <$fh>. It will read the next line from the file. At the last line, $fh will return undef which is false and loop will terminate.

Example
snippet
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.

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.

Example
snippet
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

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.

snippet
open FILE1, "file1.txt" or die $!;
...
close FILE1;

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.

snippet
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? 18 You are eligible to vote
Output
2. What is your age? 16 You are not eligible to vote.

Perl File Handle print() function

The print() function prints back the information given through filehandle operators.

snippet
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.

snippet
# 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
done

A new file file2.pl will be created in the location where file1.pl exists.

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
-A Return total access time of file since the program started.
-b Check whether file is block device or not.
-B Check whether it is a binary file.
-c Check whether file is character device.
-C Return inode change time of file since the program started.
-d Check whether file is a directory.
-e Check whether file exists or not.
-f Check type of file whether it is regular, symbolic link or other type of file.
-g Check whether file have setgid bit set.
-k Check whether file have sticky bit set.
-l Check if file is a symbolic link. In dos, it always return false.
-M Return file modification time in days since the program started.
-o Check if file is owned by an effective uid, in dos, it always return true.
-O Check if file is owned by a real uid, in dos, it always return true.
-p Check whether file is a named pipe.
-r Check whether file is readable or not.
-R Check whether file is readable by real uid or not. In dos, it is same as -r.
-s Return the file size in bytes.
-S Check if file is a socket.
-t Check if file is opened to a tty (terminal)
-T Check if file is a text file.
-u Check if file has setuid bit set.
-w Check if file is writable or not.
-W Check if file is writable by real uid/gid.
-x Check if file can be executed or not.
-X Check if file can be executed by real uid/gid.
-z 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.

Example
snippet
my $a = "/Users/rookienerd/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
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +