in reply to Delete files if they match help!

Unrelated to your problem...

Consider replacing

opendir(DIR,$dir_to_open) || die("Cannot open directory !\n"); @dir_contents= readdir(DIR); closedir(DIR); foreach $file (@dir_contents){ if(!(($file eq ".") || ($file eq ".."))){ # I want to delete the files }

with:

use File::Slurp; for my $file (grep { -f } read_dir($dir_to_open)) { # I want to delete the files }

File::Slurp is a CPAN module which abstracts away all the open/close/checking details and automatically filters out the special 'dot' directories. The grep -f selects only files.

You do use strict and warnings, don't you?

Replies are listed 'Best First'.
Re^2: Delete files if they match help!
by Anonymous Monk on Jan 07, 2011 at 15:13 UTC
    Hi, I am trying to do this like that, but I am missing something:
    use strict; use File::Slurp; ... my $dir_to_open = "../../pics"; my $arch = "../../arch"; while (my $row = $sth->fetchrow_hashref()) { for my $imgfile (map $row->{"image_$_"}, 1..4) { for my $file_to_mv (grep { -f } read_dir($dir_to_open)) { if($file_to_mv=~/$imgfile/) { #move("$dir_to_open/$file_to_mv", $arch); print "Test before move: $dir_to_open/$file_to_mv +<br>"; } } }
    Any help on this one?
      Without more details of what problem you are having, the best help I can offer is to start using print to see if your variables contain what you expect them to contain (Tip #2 from Basic debugging checklist).
        Here is what I come up:
        ... my $dir_to_open = "../../pics"; my $dir_to = "../../back"; while (my $row = $sth->fetchrow_hashref()) { for my $imgfile (map $row->{"image_$_"}, 1..4) { my $file_to_move = "$dir_to_open/$imgfile"; if (-e $file_to_move && -f $file_to_move) { move($file_to_move, $dir_to); } #.. then delete the file unlink $file_to_move if (-e $file_to_move && -f $file_to_ +move); } }

        Let me know what you think! Thanks