Directory Handling in Perl

Directory Handling Perl –

Functions used for directory handling are:

  • opendir DIRHANDLE – to open a directory
  • readdir DIRHANDLE – to read a directory
  • rewinddir DIRHANDLE – to position pointer to the start of dir.
  • mkdir DIRHANDLE – to make directory
  • rmdir DIRHANDLE – to remove directory
  • chdir DIRHANDLE – to change directory
  • closedir DIRHANDLE – to close a directory
  • seekdir DIRHANDLE – to position pointer at any specific location of directory
  • telldir DIRHANDLE – to get current position in a directory handle


open directory

opendir (DIR , “.”) or die “ Error in opening Directory, $!”;

here “.” Is current directory

read directory

while ($directory = readdir (DIR_H)) {

print “list directory: $directory \n”;


closedir DIR_H

rewind directory

my $dir_gadget = “/xyz/electronics”;

system (“rm -rf $dir_gadget”);

mkdir $dir_gadget or die $!;

my $camera = “$dir_gadget/camera”;

system (“touch $camera”);

opendir (DIR_H, $dir_gadget);

while (my $gadget = readdir (DIR_H)) {

if (-f $camera) {

unlink $camera;

rewinddir DIR_H;


Print “Directory_Path” .$gadget. “\n”;




Directory_Path .

Directory_Path ..

Directory_Path …

Create directory

$dir_name =” xyz”;

mkdir ($dir_name, $mode);

here $mode represent numeric values which is specified for unix read, write, execute permission levels.

These values are octal values

Mode Values                                     Level of Permissions

0001                                                       Execute permission to all users

0002                                                       Write permission to all users

0004                                                       Read permission to all users

0010                                                       Execute permission to group users

0020                                                       Write permission to group users

0040                                                       Read permission to group users

0100                                                       Execute permission to only owner

0200                                                       Write permission to only owner

0400                                                       Read permission to only owner

0666                                                       Read and Write permission to all users.