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

I will start by stating I am working in a Windows system running ActiveState Perl. Issue - I am trying to create a script that will travers multiple sub-directories under a static "Root" directory and look for files ending in .DAT that were modified/created on todays date. I have been able to do all but figure out how to traverse sub-dirs and only look for the .DAT files. My code so far is below - can anyone lend a hand in showing me if there is a way to traverse all subs from a given root and look for just files ending in .dat?
#!/usr/local/bin/perl opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!"; @files = readdir(DIR) closedir DIR; foreach $file (@files) { ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($file); # Will use data to create SQL statements to input data into Database }
Thanks, Ad.

Replies are listed 'Best First'.
Re: Help with ReadDir and Stat?
by moritz (Cardinal) on Mar 13, 2008 at 14:49 UTC
Re: Help with ReadDir and Stat?
by Akoya (Scribe) on Mar 13, 2008 at 15:59 UTC
    For a quick solution, without having to rely on (the far superior) modules, I've often used this code (which could certainly be improved). Just pass the starting directory on the command line.
    #!/usr/bin/perl use strict; use warnings; open my $LOG, '>', "$0.log"; my $startdir = $ARGV[0] || '.'; push my @dirs, $startdir; while (my $dir = pop @dirs) { opendir DIR, $dir; my @files = grep !/^\.\.?$/, readdir DIR; closedir DIR; foreach my $file (@files) { my $fullname = "$dir/$file"; $fullname = $file if ( $dir eq "/" ); if ( -d $fullname ) { push @dirs, $fullname; next; } if ( -f $fullname ) { if ( $file =~ /\.dat$/i ) { print $LOG $fullname . "\n"; } } } } close $LOG;
    You will of course have to add the logic for checking the tile modification time. A shortcut for that is:
    my $mtime = stat($file)[9];
    Unless, of course you need the other values that stat returns.
      Thanks, this is a huge help - in relation to the "Date" comparison - get the mod time back using the stat and that works great, but how would I do the comparison to if the file was modified or created on "Today's" date? I.E. if the file was created/modified today I want to keeps it's info - if not I will move on? Having troubles figuring out how to get to teh "Day" comparison. Thanks Again, Ad.
        You can pass the mtime to localtime. i.e.,
        my ($mday, $mon, $year) = localtime($mtime)[3,4,5];
        Then do the same with the current time:
        my ($cmday, $cmon, $cyear) = localtime(time)[3,4,5];
        and then compare them. I'm sure there's a more efficient way, but this should work.