I have a script that creates some temp files for processing later and when they are not needed anymore I want to delete them. The file that won't unlink is always the very last file that's created inside a while loop. Feels like a closing issue, but I can't see it.
Here's the relevant pieces of code:
# Creates a temp file for each of the guys with every stock item from the products listed against their name.
open ENG_LIST, 'engineer_list.txt' or die "Can't open engineer_list.txt\n";
mkdir './Temp';
while ($line = <ENG_LIST>) {
chomp $line;
@products = split(/\|/, $line);
$engineer = shift @products;
push @engineer_list, $engineer;
$fh = "./Temp/$engineer.txt";
foreach $product (@products) {
open $output, ">>:raw", "./Temp/$engineer.txt" or die "Unable to open ./Temp/$engineer.txt for appending: $!\n";
open $input, "<:raw", "./Products/$product.txt" or die "Unable to open ./Products/$product.txt for reading: $!\n";
print {$output} <$input>;
}
close ($fh);
undef @products;
}
close (ENG_LIST);
Then there's some processing I'm happy with. Then the clean up routine:
# Cleaning up all the temp files. Need to fix this because it doesn't work!
@del_files = glob ('./Temp/*.txt');
foreach $del_file (@del_files) {
chomp $del_file;
close ($del_file);
unlink "$del_file";
}
rmtree ('./Temp');
I've tried using chmod, but I'm getting nowhere with that either. The error is always
cannot unlink file - Permission denied
Instead of
close ($fh);. You would need toclose ($input);andclose ($output);. You're trying to delete/unlink()a file that is in use.