file-io beginner

How to remove a directory in Perl?

Question

How to remove a directory in Perl?

How to Remove a Directory in Perl

In Perl, the simplest and most portable way to remove a directory is using the built-in rmdir function. rmdir deletes a directory only if it is empty. It returns true on success and false on failure.

Using rmdir Correctly

The key points when using rmdir are:

  • The directory must exist.
  • The directory must be empty.
  • You need appropriate permissions to remove it.

Passing a non-existent or non-empty directory to rmdir results in failure with $! containing the error.

Perl Concepts Highlighted

  • Sigils: You use scalars ($dir) or string literals ("dirname") with rmdir. No sigil on the string literal itself.
  • Context: In scalar context, rmdir returns a boolean success indicator.
  • TMTOWTDI: Although you can call external commands like system("rmdir dir"), the built-in function is preferred for cross-platform compatibility.

Working Example

use strict;
use warnings;

my $dir = "tempdir";

# Try to create the directory for demonstration
mkdir $dir or die "Cannot create directory $dir: $!";

print "Created directory '$dir'. Now removing it...\n";

# Remove the directory with rmdir
if (rmdir $dir) {
    print "Successfully removed directory '$dir'.\n";
} else {
    warn "Failed to remove directory '$dir': $!\n";
}

This script creates an empty directory named tempdir and then removes it using rmdir. The outputs confirm whether the removal succeeded.

Common Pitfalls

  • Directory must be empty: rmdir will fail if tempdir contains any files or subdirectories.
  • Permissions: Ensure you have write permission on the parent directory.
  • Trailing slash: Avoid using something like rmdir("tempdir/") as it may not work on some systems.
  • Non-existent directory: Calling rmdir on a directory that does not exist will fail with $! set appropriately.

Removing Non-Empty Directories

Core Perl’s rmdir does not recursively delete non-empty directories. For that, modules like File::Path with remove_tree are commonly used, but they are outside the scope of a minimal example and may require enabling modules in your environment.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 7ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Created directory 'tempdir'. Now removing it...
Successfully removed directory 'tempdir'.
STDERR
(empty)

Was this helpful?

Related Questions