I’m trying to write a perl script that reads filenames in a test.txt file into an array, and then deletes the files based on the filenames in the array. Here’s what I’ve got so far…
#!/usr/bin/perl
use strict;
use warnings;
open(FILE, "test.txt") or die("Unable to open file.");
my @data = <FILE>;
close(FILE);
foreach my $line (@data){
unlink($line);
}
test.txt and remove_files.pl are in the same directory as the files to be removed. I can’t figure out why the script won’t delete the files. Am I missing a module?
Lines read from a file with the readline operator (
<...>) will include the newline character. You’ll need to remove it, or else you will be trying to delete a file called"myfile.txt\n"instead of"myfile.txt". Use Perl’schompfunction to trim your input: