Ady238 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks I need to create a script which searches in a directory for a specific pattern such as all files of *.jpg and then delete them. I have made a basic script which does this function
#!/usr/bin/perl unlink glob('C:/tmp/*/*.jpg'); unlink glob('*.jpg');
My problem is that now I need to modify it and add a clause, where if any *.jpg file is in use then the script leaves it and moves on to delete the next file. Thanks

Replies are listed 'Best First'.
Re: Delete multiple files with a pattern
by Marshall (Canon) on May 31, 2012 at 08:18 UTC
    Under Windows, there are certain types of files that can be "deleted" while they are in use (meaning that the programs that are using this file via a file handle, continue to use it even though no new program who wants to start access to this file can do it because after the "delete" no name exists in the file system, a .exe or a .dll file for example). A .jpg file is not one of those types of files.

    So if you don't care whether this file gets deleted or not, perhaps:

    #!/usr/bin/perl -w use strict; foreach my $file (glob "*.txt") { unlink $file or print "unable to delete $file\n"; }
    To delete a file that is in use, register a Run Once program or script. This requires a reboot.
    Perl "unlink" can do things that you cannot do from another Windows command line window, e.g. "delete" a .dll, etc.

Re: Delete multiple files with a pattern
by Anonymous Monk on May 31, 2012 at 07:06 UTC
    no such thing really, either you can delete it, or you can't
    use autodie; open my($fh), q/>/, 2; flock $fh, 2; eval { unlink 2; } or warn $@; close $fh; unlink 2; unlink 2; __END__ Can't unlink('2'): Permission denied at - line 4 Can't unlink('2'): No such file or directory at - line 7