deleting files with perl

不问归期 提交于 2019-12-01 07:32:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!