← Back to Perl Course | Chapter 5: File I/O | Lesson 6 of 7

Directories

opendir, readdir and mkdir let you create and list folders.

In this page:

  1. Directories

Directories

mkdir creates a directory and rmdir removes an empty one. opendir gives a directory handle, and readdir returns its entries, including the special names . and .. which you normally skip. The order of readdir results is not defined, so sort them for predictable output.

Note: The glob function, such as glob("*.txt"), returns matching file names without opening a directory handle.

Example: Directories

perl
use strict;
use warnings;

my $dir = "demo_dir";
mkdir $dir or die "Cannot mkdir: $!" unless -d $dir;
for my $name (qw(b.txt a.txt c.log)) {
    open(my $fh, '>', "$dir/$name") or die "Cannot create $name: $!";
    print $fh "x\n";
    close $fh;
}
opendir(my $dh, $dir) or die "Cannot open dir: $!";
my @entries = sort grep { $_ ne '.' && $_ ne '..' } readdir($dh);
closedir $dh;
print "entries: @entries\n";
my @txt = map { s{^\Q$dir\E/}{}r } sort glob("$dir/*.txt");
print "txt files: @txt\n";
unlink glob("$dir/*");
rmdir $dir or die "Cannot rmdir: $!";
print "directory removed: ", (-d $dir ? "no" : "yes"), "\n";

# Output:
# entries: a.txt b.txt c.log
# txt files: a.txt b.txt
# directory removed: yes
Common Mistakes
  1. Forgetting that readdir also returns . and ..
  2. Assuming readdir returns names in sorted order
  3. Trying to rmdir a directory that is not empty
Chapter Summary
  • mkdir and rmdir create and remove directories
  • opendir and readdir list entries
  • Skip . and ..
  • Sort names for stable order
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.