Accessing Files and Directories in Perl - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Accessing Files and Directories in Perl

Share This

To work with files and directories in Perl, you have to understand filehandles. A filehandle is a named internal structure which is associated with a file name. It is used to perform read/write/update operations on files.

The basic filehandles are STDIN for standard input, STDOUT for standard output, and STDERR for standard error devices.

Open Function

To open a file in read-only mode, < symbol is used with file name. In the following example, DATA is the file handle.

open(DATA, "<sample.txt");

In this context to print the content of the file on terminal, a loop can be used to iterate over DATA as shown below.


#!/usr/bin/perl open(DATA, "<sample.txt") or die "Unable to open $!"; while(<DATA>) { print "$_"; }

To open sample.txt in writing mode, > symbol is used before the file name as shown below. Note that, in this mode the file is truncated (previous content is deleted).


open(DATA, ">file.txt") or die "Unable to open file $!";

If a file needs to be opened for both reading and writing, the plus sign (+) needs to be added before the > or <.

To open a file for updation without truncation, open the file as


open(DATA, "+<sample.txt"); or die "Unable to open file $!";

To truncate the file, you can use


open DATA, "+>sample.txt" or die "Unable to open file $!";

To open a file in append mode (file pointer is set at the end), you can use the follwing.




open(DATA,">>sample.txt") || die "Unable to open file $!";

But in this case, read operation can not be performed.

To perform append along with read operation, you can use




open(DATA,"+>>sample.txt") || die "Unable to open file $!";

Sysopen Function

In this function, the parameters are passed to it as the parameters for the system function. To open a file for updation, instead of using +< , the file is opened as




sysopen(DATA, "sample.txt", O_RDWR);

or to truncate the file before updation




sysopen(DATA, "sample.txt", O_RDWR|O_TRUNC );

To create a new file O_CREAT can be used. Similarly, O_WRONLY and O_RDONLY can be used to open file in write only mode and read only mode respectively.

Close Function

To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle's buffers and closes the system's file descriptor.

The function close(FILEHANDLE) is used to close a specific filehandle, by flushing buffer and closing filedescriptor.

If filehandle is not specified, the currently selected filehandle is closed.




close(DATA) || die "Unable to close file!";

Reading and Writing Files

The content of a file can be read by using a filehandle operator as shown below.




#!/usr/bin/perl print "Where do you live?\n"; $name = <STDIN>; print "$name\n";

To import content of a file having many lines, we can try the following program.




#!/usr/bin/perl open(DATA,"<sample.txt") or die "Unable to olpen file!"; @lines = <DATA>; close(DATA);

Copying Files

The following program can be used to open an existing file, read the content line by line and copy the content in another file.




#!/usr/bin/perl open(fhold, "<old.txt"); open(fhnew, ">new.txt"); while(<fhold>) { print fhnew $_; } close(fhold); close(fhnew);

Renaming a file

The function rename can be used to rename a file as shown below.




#!/usr/bin/perl rename ("/usr/test/fold.txt", "/usr/test/fnew.txt" );

Deleting an Existing File

The unlink function can be used to delete an existing file.




#!/usr/bin/perl unlink ("/usr/test/myfile.txt");

Positioning inside a File

tell Function

The tell function, returns current position (in Bytes) of the cursor within a file.




tell FILEHANDLE

seek Function

The seek function is used to move the cursor to a specific location within the file




seek DATA, 256, 0;

Here zero (0) sets the positioning relative to the start of the file.

File Information

To get file permission related information, we can run the following code.




#/usr/bin/perl my $file = "/usr/test/file1.txt"; my (@description, $size); if (-e $file) { 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 "$file is ", join(', ',@description),"\n"; }

Following are the standard functions used to play with directories.




opendir DIRHANDLE, EXPR # To open a directory readdir DIRHANDLE # To read a directory rewinddir DIRHANDLE # Positioning pointer to the begining telldir DIRHANDLE # Returns current position of the dir seekdir DIRHANDLE, POS # Pointing pointer to POS inside dir closedir DIRHANDLE # Closing a directory.

Display all the Files

To get list of files available in a particular directory, the glob operator is used as shown below.




#!/usr/bin/perl $dir = "/tmp/*"; my @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } $dir = "/tmp/*.c"; @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } $dir = "/tmp/.*"; @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } $dir = "/tmp/* /home/*"; @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; }

The following program shows the list of files available inside a directory.




#!/usr/bin/perl opendir (DIR, '.') or die "Unable to open directory, $!"; while ($file = readdir DIR) { print "$file\n"; } closedir DIR;

Create Directory

The mkdir function is used to create a new directory.




#!/usr/bin/perl $dir = "/tmp/perl"; mkdir( $dir ) or die "Unable to create directory $!"; print "Successful\n";

Remove a directory

The rmdir function is used to remove a directory from file system. The user should have proper permission, moreover the directory should be empty.




#!/usr/bin/perl $dir = "/tmp/perl"; rmdir( $dir ) or die "Unable to remove directory $!"; print "Successful\n";





Change a Directory

To move to a new directory location, chdir function is used. Note that the user should have proper permission.




#!/usr/bin/perl $dir = "/home/test/demo"; chdir( $dir ) or die "Unable to perform change directory $!"; print "Your new location is $dir\n";


Happy Exploring!

No comments:

Post a Comment