[prog] Perl and find(1)
Jacinta Richardson
jarich at perltraining.com.au
Mon Dec 11 05:05:30 UTC 2006
Perl has its own built-ins for many common Unix functionality. For example if
you want a list of files, you're better off using glob() or readdir() rather
than system and ls.
This increases portability and maintenance of your programs. It's also easier
to check whether things succeeded. Calling out to system also slows down your
program.
In this case you're likely again to be better off using Perl's File::Find
module. File::Find comes standard with the Perl distribution.
Chris Henderson wrote:
> I wrote this script which will go inside some directories and delete
> files but the find(1) command says "-exec" missing. Is it because I'm
> not parsing ls correctly?
I can't even get the find command to work outside of Perl:
jarich at bella:/tmp$ find . -atime +14 -name "*.tgz" -print -exec "ls -al"
find: missing argument to `-exec'
So your error is there.
Anyway, to rewrite this:
> #!/usr/bin/perl
>
> use strict;
> use warnings;
> use diagnostics;
use File::Find;
>
> my @directories = qw(
> /home/backup/server1
> /home/backup/server2
> /home/backup/server3
> );
find(\&wanted, @directories);
sub wanted {
return unless ( /\.tgz$/ ); # ignore non .tgz files
return unless ( -A $_ > 14 ); # skip if less than 14 days old
print; # print name of file
}
More information about the Programming
mailing list