Broad Network


Perl Filehandle and File Name

Handling Files and Directories in Perl – Part 3

Perl Course

Foreword: In this part of the series I talk about the file as an entity.

By: Chrysanthus Date Published: 27 Aug 2015

Introduction

This is part 1 of my series, Handling Files and Directories in Perl. In this part of the series I talk about the file as an entity. You should have read the previous parts of the series before coming here, as this is a continuation. For simplicity, the text files we deal with are in the working directory. The working directory is the directory that has the Perl script. In this tutorial, frequently asked questions are also answered.

Opening and Closing Files
The syntax to open a file for reading is:

        open(fHandle, "<", "input.txt") or die "cannot open input.txt : $!";

where fHandle is declared and used at that point. < is the sign to open a file for reading. Under this condition, < means open file only to read its content. input.txt is the file name in quotes.

The syntax to open a file for writing is:

        open(fHandle, ">", "output.txt") or die "cannot open output.txt : $!";

where fHandle is declared and used at that point. > is the sign to open a file for writing. Under this condition, > means open file to write content; erase any previous content that the file might have had; if file did not exist in disk, create one.

To close a file, whether for reading or writing, the syntax is:

    close(fHandle) or die "cannot close file : $!";

where fHandle is the filehandle used in opening the file. When a file is closed successfully, you break the association between the file in memory and the file in disk; any part of the file that was still in memory, is flushed to the disk.

fileno
At the low-level of Perl, the filehandle is a number. fileno is a function which can return the number called, file descriptor. If the filehandle is not opened, the function returns undef. If there is a filehandle, but the file exists only in memory and not in disk, the function returns –1. The following code segment returns the file descriptor for an opened filehande and assigns the number to the $no variable.

    open(fHandle, "<", "myFile.txt") or die "cannot open file: $!";
    my $var = fileno(fHandle);
    print $var;
    close(fHandle);

I tried the code in my computer and I had the decimal number, 3.

Renaming a File
You can change the name of a file, say from myFile.txt to input.txt The file should not be opened before you rename it. You use the rename function. The function returns true for success and false otherwise. The following statement illustrates this:

    rename("myFile.txt", "input.txt");

Deleting a File
To delete a file, you use the unlink function. You can delete more than one file. On success it returns the number of files successfully deleted. On failure (no file deleted), it returns false and sets the special $! error variable. You should not open the files before you delete them. Assume that you want to delete the files, one.txt and two.txt, you would type:

use strict;

    my $no = unlink('one.txt', 'two.txt');

    if (!$no)
        {
            print "error: $!";
        }
    else
        {
            print "No. of files deleted: $no";
        }

Expanding Filenames Using Wildcards
Imagine that you have files in a directory, which have the .txt and .doc extensions. You can copy the actual names of all these files to an array, as follows:

    my @arr = glob("*.txt *.doc");

Note that the glob function has one argument, which is a string. Each file pattern is separated by a space (not comma) in the string. Note the use of the wildcard character, * in the patterns. There is more to the argument of the glob function, than I have said here. You will consult some other document for that. The following code displays the actual filenames in the array:

use strict;

    my @arr = glob("*.txt *.doc");

    print "$_, " foreach (@arr);

The last statement is an example of a simple Perl statement, where the action comes before the statement modifier.

Filehandle as a Scalar Variable
You can create a filehandle as a scalar variable, but this has to be done in the open() function, as in:

    open(my $fh, ">", "output1.txt") or die "cannot open output1.txt : $!";

where $fh is a scalar variable and at the same time, a filehandle.

A filehandle as a scalar variable, comes with some advantages.

Printing to more than one file at Once
The obvious way to print to more than one file at once is as follows:

     print $_ "something " foreach (filehandle1, filehandle2, filehandle3 . . .);

Try the following code:

use strict;

    open(my $fh1, ">", "output1.txt") or die "cannot open output1.txt : $!";
    open(my $fh2, ">", "output2.txt") or die "cannot open output2.txt : $!";
    open(my $fh3, ">", "output3.txt") or die "cannot open output3.txt : $!";

    print $_ "I love you." foreach ($fh1, $fh2, $fh3);

    close $fh1; close $fh2; close $fh3;

For the foreach loop to work, the filehandle has to be a scalar variable. Remember, making the filehandle a scalar variable can give you more flexibility in coding. The foreach loop is an example of a simple statement, where the action comes before the statement modifier.

File Test
You can test whether a file is empty; you can test whether a file even exist; you can test other issues for a file. The test syntax is:

-X FILEHANDLE

This is an example of what is called, a unary operator. It returns true if the test is true or false if the test is false. You do not use X for the different tests; you use a letter like z, or s. The following list gives some of the letters and what they test.

    -e  File exists.
    -z  File has zero size (is empty).
    -s  File has nonzero size (returns size in bytes).
    -f  File is a plain file.
    -d  File is a directory.
    -b  File is a block special file.
    -c  File is a character special file.
    -T  File is an ASCII text file (heuristic guess).
    -B  File is a "binary" file (opposite of -T).
    -M  Script start time minus file modification time, in days.  

Try the following code which tests if a file exists.

use strict;

    open(fHandle, "<", "myFile.txt") or die "cannot open myFile.txt : $!";

    print "File exists." if -e fHandle;

    close(fHandle);

The test statement is an example of a simple statement, where the action comes before the statement modifier (if).

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message