问题
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?
回答1:
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's chomp function to trim your input:
foreach $line (@data){
chomp($line);
unlink($line);
}
来源:https://stackoverflow.com/questions/9265523/deleting-files-with-perl