1. Perl
  2. builtin functions
  3. here

readdir function - reads the contents of a directory

Use the readdir function to read the contents of the directory.

readdir directory handle

Specify the directory handle obtained by opendir function. The return value is the name of the file in the directory. You can read all the files in the directory by calling it repeatedly.

Let's write an example program that gets the directory handle with the opendir function and reads all the files with the readdir function. I use while statement to get the file names one by one.

# Directory name
my $dir = 'study';

# Open directory
opendir my $dh, $dir
  or die "Can't open directory $dir:$!";

# Read all files
while (my $file = readdir $dh) {
  print "$file\n";
}

The output result is a list of file names included in the directory as shown below.

..
..
a.txt
b.txt

Note that it contains a "." That represents the current directory and a ".." that represents a directory one level higher.

Normally, I don't think you need "." Or "..". So use next statement and skip if these two are true.

# Read all files
while (my $file = readdir $dh) {
  next if $file eq '.' || $file eq ' ..';
  print "$file\n";
}

This will give you the results you want.

If you want to make the file list array without outputting it, write as follows.

my @files;
while (my $file = readdir $dh) {
  next if $file eq '.' || $file eq ' ..';
  push @files, $file;
}

How to get a list of files including subdirectories?

If you want to process files recursively, including subdirectories, you should use the File::Find module.

Please tell me how to use it properly with the glob function

In Perl, you can get a list of filenames by using glob function without using the directory handle.

The glob function has the following advantages:

  • "." ".." is not included
  • There is no need to loop. Convenient to combine with grep function.
  • You can get the full path of the file name instead of the base name
  • You can use the wildcard "*"

Frankly speaking, the readdir function doesn't come into play very often, and it's easy to use the glob function to get a list of filenames.

I think that it is indispensable when you want to see the file list exactly in directory units like the implementation of File::Find. The glob function is useful for everyday use.

Related Informatrion