I recently signed up for the perl Ironman challenge at http://www.enlightenedperl.org/ironman.html. I've had this blog sitting around for a long time (maybe 7 years) but never posted to it. I've been using my blog "The Red Stallion Patrol" for all my posts, but wanted to separate out my perls of wisdom. This is a cross post of an item I posted 4 days ago.
Here's the code I use to cycle through all the files in a sub-directory, make sure they exist and have a non-zero size. If this all passes, process the file. I use this pretty frequently at work to do "something interesting" with all files in a sub-directory (folder to you windows users) that may contain any number of files (probably added to daily) of a certain type.
#!/usr/bin/perl
use warnings;
use strict;
my $DIR = "/some/directory";
my $inputfile = $ARGV[0];
# ----- Go through all the files in a directory
my $InputDir = join("/", $DIR, $inputfile);
opendir (ARCHIVE, $InputDir ) or die "can't opendir ARCHIVE $InputDir: $!";
my @InputDirFiles = grep { -f } # select files only
map { "$InputDir/$_" } # IMPORTANT - prepend directory name
grep { ( $_ ne '.' ) and ( $_ ne '..' ) } # throw out dots entries
readdir ARCHIVE;
closedir ( ARCHIVE ) or warn "can't closedir ARCHIVE: $!";
local $, = "\n";
foreach my $CurrentFile (@InputDirFiles) {
# ----- Does the file exist?
(my $dev,my $ino,my $mode,my $nlink,my $uid,my $gid,my $rdev,my $size,my $atime,my $mtime,my $ctime,my $blksize,my $blocks)
= stat("$CurrentFile");
if (-e _) {
printf "\t$CurrentFile exists.\n";
if (-z _) {
printf "\t\tIt is zero bytes\n";
exit;
}
if (-s _) {
printf "\t\tIt is $size bytes long\n";
# ----- at this point the file exists and has size.
# you could open it and have your way with it.
}
} else {
printf "\tDidn't find $CurrentFile\n";
exit;
}
# ----- You could also wait until this point to
# open it and have your way with it.
}
No comments:
Post a Comment