system-admin intermediate

How to delete files older than 30 days in Perl?

Question

How to delete files older than 30 days in Perl?

Deleting files older than a specific age—such as 30 days—is a common task in system administration and automation. Perl, with its strong filesystem handling capabilities, offers a flexible way to accomplish this. Below, I'll explain how to identify files older than 30 days and delete them safely using Perl's built-in functions.

Understanding the Approach

  • Use opendir and readdir to read the directory contents.
  • For each file, fetch the file's modification time using stat.
  • Compare the modification time to the current time minus the age threshold (30 days).
  • If the file is older, delete it using unlink.

Common pitfalls include:

  • Attempting to delete directories instead of files—make sure you verify the file type.
  • Accounting for hidden files (those starting with a dot) if needed.
  • Handling filename encoding issues or special characters.
  • Ensuring you have proper permissions to delete the files.

This example covers the core logic on Perl 5.10+ and uses strict and warnings pragmas for safer code.

Perl Code Example: Delete Files Older Than 30 Days


use strict;
use warnings;

# Directory to clean up
my $dir = '.';

# Define age threshold (30 days in seconds)
my $days_old = 30;
my $age_threshold = time() - ($days_old * 24 * 60 * 60);

# Open the directory or die with an error message
opendir(my $dh, $dir) or die "Cannot open directory '$dir': $!";

# Process each entry in the directory
while (my $file = readdir($dh)) {
    next if $file eq '.' or $file eq '..';  # Skip current and parent dir

    my $path = "$dir/$file";

    # Only process files, skip directories and others
    next unless -f $path;

    my $mtime = (stat($path))[9];
    unless (defined $mtime) {
        warn "Could not stat $path: $!";
        next;
    }

    # Check if modification time is older than threshold
    if ($mtime < $age_threshold) {
        # Attempt to unlink (delete) the file
        if (unlink $path) {
            print "Deleted old file: $path\n";
        } else {
            warn "Failed to delete $path: $!";
        }
    }
}

closedir($dh);

Explanation of Key Concepts

  • opendir, readdir, and closedir handle reading directory contents, a common primitive in Perl for filesystem traversal.
  • -f is a file test operator verifying that the path is a plain file, avoiding directories or special files.
  • stat (in list context) returns an array of file attributes; index 9 corresponds to the modification time (mtime).
  • time() returns the current epoch time (seconds since 1970-01-01 UTC).
  • Arithmetic on times calculates the cutoff for "30 days ago" precisely.
  • unlink deletes files, returning true on success, false on failure.

Additional Tips

  • Modify $dir to the desired directory path.
  • You could extend this script to operate recursively—using modules like File::Find (core module), but this example keeps it simple and direct.
  • Be careful running scripts that delete files—always test with print statements before uncommenting unlink to avoid accidental data loss.
  • For Windows environments, ensure path separators and permissions behave as expected.

This example demonstrates core Perl idioms, making it easy to customize for various cleanup tasks and illustrate Perl’s “There's More Than One Way To Do It” (TMTOWTDI) philosophy.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions