Here are some examples of common operations you might perform on directories in Perl:

Perl Directory Examples

Listing the contents of a directory:

  • Open the directory

opendir(my $dh, ‘/path/to/dir’) or die “Could not open directory: $!”;

  • Read the contents of the directory

my @files = readdir($dh);

  • Close the directory

closedir $dh;

print “Files in directory:\n”; foreach my $file (@files) { print “$file\n”; } Creating a new directory: Copy code use File::Path qw(make_path);

Create a new directory

make_path(’/path/to/new/dir’) or die “Could not create directory: $!”; Removing a directory: Copy code use File::Path qw(remove_tree);

Remove a directory and all its contents

remove_tree(’/path/to/dir’) or die “Could not remove directory: $!”; Changing the current working directory: Copy code use Cwd;

Change to a new directory

chdir ‘/path/to/new/dir’ or die “Could not change directory: $!”;

print “Current directory: “, getcwd(), “\n”; Checking if a path is a directory: Copy code use File::stat;

Check if a path is a directory

my $path = ‘/path/to/dir’; my $stat = stat($path); if ($stat and $stat->isdir) { print “$path is a directory.\n”; } else { print “$path is not a directory.\n”; } These are just a few examples of the types of operations you can perform on directories in Perl. There are many other functions and modules available for working with directories and files in Perl.