Different operating systems have different commands to look at the files list within a directory. For example, 'li' command is used for Linux and 'dir' command is used for Windows.
But we can also open a directory in Perl using Perl directory functions. Here, Directory handling is quite similar to file handling.
Perl provides two alternatives for directories: file globbing and directory functions. File globbing is usually used for a similar subset of files whereas directory functions provide more options.
Perl Directory Functions
In the given table, we have listed some of the directory functions.
Perl Open/Display Directory
To open a directory in Perl, there is a function opendir. This function returns true on success or false on failure.
Setting $! with actual error message will display a reason for the failure.
Perl Create Directory
To create a new directory in Perl, there is a function mkdir. You need required permission to create a directory.
Directory created successfully
Given snapshot shows created directory perl in the /users/javatpoint directory list.
Perl Read Directory in SCALAR context
To read content of a directory, function readdir is used. In scalar context, this function will return each item of a directory one by one. Once everything is read out, it will return undef.
Perl Read Directory in LIST context
In list context, readdir function will return all the content of directory in one statement. So it uses more memory.
Perl Remove Directory
To remove a directory in Perl, there is a function rmdir. You need required permission to remove a directory. The directory which you want to remove should be empty before removing it.
Directory removed successfully
Perl Change Directory
To change a directory in Perl, there is a function chdir. To change a directory and go inside a new directory you need required permission.
Diretory has been changed to /users/
Perl Close Directory
To close a directory in Perl, there is a function closedir. This function officially shut down the connection between directory handle and directory. Although, closing directory is not mandatory in Perl because directory will be automatically closed when variable goes out of scope.
Perl Opening Directory using File Globbing
To open all files in a directory matching a specific pattern, use Perl filename glob matching pattern syntax.
We'll display the list of all the files having extension .docx in a directory.
In the above output, all the files are read in the directory, but grep only passes files with .docx extension.