file-io intermediate
How to read directory contents in Perl?
Question
How to read directory contents in Perl?
Reading directory contents in Perl is commonly done using opendir, readdir, and closedir. These built-in functions allow you to open a directory handle, read the entries, and close the handle when done.
A key point is to properly interpolate variables in strings. If you want to include a variable like $dir inside a double-quoted string, ensure the string is correctly quoted, and no conflicting quotes break your code.
Fixed runnable example
#!/usr/bin/perl
use strict;
use warnings;
# Directory to read, current directory is "."
my $dir = '.';
# Open directory handle, die on error
opendir(my $dh, $dir) or die "Cannot open directory '$dir': $!";
# Read all entries except '.' and '..'
my @files = grep { $_ ne '.' && $_ ne '..' } readdir($dh);
# Close directory handle
closedir($dh);
# Print directory contents
print "Contents of directory \"$dir\":\n";
foreach my $file (@files) {
print "$file\n";
}
Here are some Perl-specific points:
- Sigils: The variable
$dirholds the directory path. The directory handle$dhis a scalar but acts like a filehandle. - Context: Using
readdirin list context returns all entries at once, which we filter usinggrep. - TMTOWTDI: You could also read entries one by one using a
whileloop in scalar context withreaddir.
Common Pitfalls:
- Make sure strings containing variables are properly quoted. For example, use double quotes with escaped internal quotes, or use separate
printarguments. - Always check the return value of
opendirand handle errors. - Remember to exclude
.and..entries as they usually aren’t useful when listing directory content.
This example works on Perl 5.6 and later without additional modules and completes quickly without external dependencies.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 6ms
Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Contents of directory ".":
.bun-cache
database
tooling
example_copy.txt
.DS_Store
frontend
perl-qa-batch1.json
Makefile
gemini-perl.json
markz_status.txt
filename.txt
example_source.txt
backend
docs
README.md
.env
processed_profile.txt
scripts
advanced-perl-challenges.json
api
docker-compose.yml
perl-qa-batch2.json
.tmp
filename
.env.example
AGENTS.md
data
front
output.txt
CLAUDE.md
perl-qa-batch3.json
STDERR
(empty)Was this helpful?
Related Questions
- How to use File::Find to recursively search directories in Perl?
- How to use Path::Tiny for file operations in Perl?
- How to use File::Copy to copy files in Perl?
- How to get file modification time in Perl?
- How to use File::Slurp to read files in Perl?
- How to open a file with specific encoding in Perl?