Accessing Files and Directories in Perl - BunksAllowed

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

Community

demo-image

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.

1
2
3
open(DATA, "<sample.txt");
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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


1
2
3
4
5
6
7
8
9
#!/usr/bin/perl
open(DATA, "<sample.txt") or die "Unable to open $!";
while(<DATA>) {
print "$_";
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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


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

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


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

To truncate the file, you can use


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

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




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

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

To perform append along with read operation, you can use




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

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




1
2
3
sysopen(DATA, "sample.txt", O_RDWR);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

or to truncate the file before updation




1
2
3
sysopen(DATA, "sample.txt", O_RDWR|O_TRUNC );
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.




1
2
3
close(DATA) || die "Unable to close file!";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Reading and Writing Files

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




1
2
3
4
5
6
7
#!/usr/bin/perl
print "Where do you live?\n";
$name = <STDIN>;
print "$name\n";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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




1
2
3
4
5
6
7
#!/usr/bin/perl
open(DATA,"<sample.txt") or die "Unable to olpen file!";
@lines = <DATA>;
close(DATA);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.




1
2
3
4
5
6
7
8
9
10
#!/usr/bin/perl
open(fhold, "<old.txt");
open(fhnew, ">new.txt");
while(<fhold>) {
print fhnew $_;
}
close(fhold);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Renaming a file

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




1
2
3
4
5
#!/usr/bin/perl
rename ("/usr/test/fold.txt", "/usr/test/fnew.txt" );
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Deleting an Existing File

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




1
2
3
4
5
#!/usr/bin/perl
unlink ("/usr/test/myfile.txt");
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Positioning inside a File

tell Function

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




1
2
3
tell FILEHANDLE
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

seek Function

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




1
2
3
seek DATA, 256, 0;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.




1
2
3
4
5
6
7
8
9
10
#/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 _);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Following are the standard functions used to play with directories.




1
2
3
4
5
6
7
8
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.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Display all the Files

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




1
2
3
4
5
6
7
8
9
10
#!/usr/bin/perl
$dir = "/tmp/*";
my @files = glob( $dir );
foreach (@files ) {
print $_ . "\n";
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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




1
2
3
4
5
6
7
8
9
#!/usr/bin/perl
opendir (DIR, '.') or die "Unable to open directory, $!";
while ($file = readdir DIR) {
print "$file\n";
}
closedir DIR;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Create Directory

The mkdir function is used to create a new directory.




1
2
3
4
5
6
7
8
#!/usr/bin/perl
$dir = "/tmp/perl";
mkdir( $dir ) or die "Unable to create directory $!";
print "Successful\n";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.




1
2
3
4
5
6
7
#!/usr/bin/perl
$dir = "/tmp/perl";
rmdir( $dir ) or die "Unable to remove directory $!";
print "Successful\n";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX





Change a Directory

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




1
2
3
4
5
6
7
#!/usr/bin/perl
$dir = "/home/test/demo";
chdir( $dir ) or die "Unable to perform change directory $!";
print "Your new location is $dir\n";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.