7.1. Directory Input Routines

The opendir DIRHANDLE, EXPR function can be used to open the directory EXPR for reading its file and sub-directory entries. Afterwards readdir(DIRHANDLE) can be used to read one entry from there, or all the entries if used in list context.

Use closedir() to close an opened directory.

Here's an example that counts the number of mp3s in a directory:

#!/usr/bin/env perl

use strict;
use warnings;


sub get_dir_files
{
    my $dir_path = shift;

    opendir D, $dir_path
        or die "Cannot open the directory $dir_path";

    my @entries;
    @entries = readdir(D);
    closedir(D);

    return \@entries;
}

my $dir_path = shift || ".";

my $entries = get_dir_files($dir_path);
my @mp3s = (grep { /\.mp3$/ } @$entries);

print "You have " . scalar(@mp3s) . " mp3s in $dir_path.\n";

Written by Shlomi Fish