How to display list of files in a directory using Perl?

Here, we will show you to display the list of files in a particular directory using Perl?
Submitted by Godwill Tetah, on December 12, 2020

We will use a Perl inbuilt function known as DIR which means directory handler just as we also have File Handler.

This built-in Perl module has the ability to open a directory and read the content of the directory. So today, we will code a simple program that opens a directory a list the content of the directory, meaning its files and folders.

We will use assign the DIR output to an array and then use the foreach loop to get a list of the directory's content.

The code below is an implementation of the above explanation.

Program/Source Code:

File name:

#checking directory content using Perl

opendir( DIR, "E:\\PERL\\" );
@x = readdir(DIR);
foreach (@x) {
    print "$_\n";

Below are some points to take note of;

  • Notice the way I wrote my directory.
  • The body of the foreach loop has the symbol $_ which represents the content of the array.
  • Finally, the directory is closed using closedir(DIR).


Display list of files in a directory using Perl

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.