Perl File Delete: Deleting Files and Directories in Perl

To delete a file in Perl, use the unlink function.

unlink("hello.txt");




... deletes hello.txt.

If for some reason unlink doesn't work (which seems to happen under certain circumstances), don't forget you can always just exec operating system commands if portability is not necessary for your Perl program.

`del hello.txt`;




The backtics here (not to be confused with quotes) run an operating system command. I've found that on some systems and under certain circumstances, expressions placed between backtics don't seem to execute. I don't know why this happens, but if you have this problem, try putting the commands you want to execute in a string, and then put the string between the backtics.

my $command = "del hello.txt";
`$command`;




You can also use exec of course.

exec("del hello.txt");






Checking If A File Has Correctly Been Deleted



How do you know if your file deletion succeeded? You can use the file test operators, -e for instance, to check if the file is still present or not. -e checks if the file or directory exists.

my $file = "hello.txt";

unlink $file;

if(-e $file) 
{
    print "File still exists!";
}
else 
{
    print "File gone.";
}





File gone.




A simpler way is just to check the return value from unlink. unlink returns the number of files it has deleted.

my $file = "hello.txt";
    
my $removed = unlink($file);
    
print "Removed $removed file(s).\n";




Removed 1 file(s).




If you want to delete more than one file with unlink, you can supply unlink with a list of files to delete -- either by specifying multiple comma-separated arguments to unlink, or equivalently by supplying unlink with an array of names of files to delete.

my @files = ('hello.txt', 'temp.txt');
    
my $removed = unlink(@files);
    
print "Removed $removed file(s).\n";




Removed 2 file(s).




Deleting a Directory in Perl



You can delete a directory in Perl using rmdir.


my $dir = "hello";

rmdir $dir;

if(-e $dir) 
{
    print "Directory '$dir' still exists";
}
else 
{
    print "Directory '$dir' deleted.";
}





Directory 'hello' deleted.




However, this will fail if the directory isn't empty. To delete non-empty directories, you need rmtree from the File::Path module. Careful with this!

use strict;
use warnings;

use File::Path;

sub main
{

    my $dir = "hello";

    rmtree $dir;

    if(-e $dir) 
    {
        print "Directory '$dir' still exists";
    }
    else 
    {
        print "Directory '$dir' deleted.";
    }


}

main();





Directory 'hello' deleted.