Directories
opendir, readdir and mkdir let you create and list folders.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that readdir also returns . and ..
- Assuming readdir returns names in sorted order
- 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: