Thursday, March 31, 2011

Perl Script: Delete All Files and Folders in a Directory

use strict;
use warnings;

# Start the recursive cleanup process on the target directory
cleanup("d:/tempo");

sub cleanup {
    # Get the directory path passed to the subroutine
    my $dir = shift;
    
    # Localize the directory handle and open the directory
    local *DIR;
    opendir(DIR, $dir) or die "Cannot open directory $dir: $!";
    
    # Loop through each item (file or folder) inside the directory
    for my $file (readdir(DIR)) {
        
        # Skip the special current (.) and parent (..) directory entries
        next if $file =~ /^\.{1,2}$/;
        
        # Construct the full path to the current item
        my $path = "$dir/$file";
        
        # If the item is a regular file, delete (unlink) it
        unlink $path if -f $path;
        
        # If the item is a directory, call this subroutine recursively to empty it
        cleanup($path) if -d $path;
        
        print "Deleting $path\n";   
    }
    
    # Close the directory handle once we are done reading its contents
    closedir(DIR);
    
    # Finally, remove the now-empty directory itself
    print "Removing directory $dir\n";
    rmdir $dir or print "Error removing $dir: $!\n";
}

No comments: