in reply to Delete files if they match help!

Maybe I'm misunderstanding... but can't you just try to delete the files returned from the db query — rather than search through and compare with the entire directory listing every time?  If the file doesn't exist in the directory, the unlink call will fail, but so what? it isn't going to hurt the computer.  Something like this:

while (my $row = $sth->fetchrow_hashref()) { for my $imgfile (map $row->{"image_$_"}, 1..4) { unlink "../../pics/$imgfile"; } }

And if you don't really care which individual files couldn't be unlinked (by checking the function's return value), you could also pass the entire file list directly to a single unlink call...

unlink map "../../pics/".$row->{"image_$_"}, 1..4;

Replies are listed 'Best First'.
Re^2: Delete files if they match help!
by Anonymous Monk on Jan 07, 2011 at 04:08 UTC
    I like this:
    while (my $row = $sth->fetchrow_hashref()) { for my $imgfile (map $row->{"image_$_"}, 1..4) { unlink "../../pics/$imgfile"; } }
    But I will move the files somewhere else instead of deleting it.
Re^2: Delete files if they match help!
by Anonymous Monk on Jan 07, 2011 at 14:43 UTC
    Well, in the database only the name of these files exist, in the directory in spec is where the physical files are, that’s why I need to check if they match first before deleting them, any more feedback? Thanks!

      I'm afraid I still don't understand the need for the extra checking.  If you have a name, say "img_2678.jpg", in the DB that you want to delete from the directory ../../pics, you'd just create the proper path and do

      unlink "../../pics/img_2678.jpg";

      The OS will then try to locate the physical file and, if it's there, delete it.  If it's not there, the unlink call will fail. That's it. No need to first figure out if the directory holds a file img_2678.jpg.

      Or is it that you don't know which directory holds the files? In this case, just check the return value of the unlink call. If it succeeded, you likely picked the right one, otherwise try the next directory candidate.

      (The same general considerations would apply if you're actually going to move the files, instead of deleting them.)