Working with Directories in Perl

Advertisement

Advertisement

This example shows how to list the contents of directories in Perl. It also demonstrates how to change directories, create directories, differentiate between files and directories, and use a regular expression to limit the results or search for particular file names or extensions.

Check if Directory Exists

if ( -d "/home/NanoDano/testDir") {
    print "Directory exists";
}

Create Directory

mkdir '/home/NanoDano/tmp';

Change Directory Permissions

chmod(0755, $dirPath);

Change Directory

chdir '/home/NanoDano/perl';

List Contents of Directory

my $directory = '/tmp';

opendir(DIR, $directory);

while (my $filename = readdir(DIR)) {

# Skip unless it is a file
next unless (-f "$directory/$filename");

# Use regex to limit only to .jpg files
next unless($filename =~ m/\.jpg$/);

print "$filename\n";
}
closedir(DIR);

Advertisement

Advertisement