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

I must be making a simple mistake here... I am just trying to recurse through a directory and list all the files with their parent directory, sizes and dates. It's not working... I get the filenames and parent directory, but size and date are blank. I'm trying both -s and stat to get the size and neither one works. I imagine that I'm not accessing the file correctly to stat it, but I don't see what is wrong. Any help is appreciated - thanks!
use File::Find; $rootdir = "testdir"; find(sub { if (-f) { $file = $File::Find::name; $dir = $File::Find::dir; ($size,$date) = (stat $file)[7,9]; $sz = -s $file; $file =~ s/$dir\///g; $dir =~ s/\//\\/g; print "file:$file\ndir:$dir\nsize1:$size\nsize2:$sz\ndate:$date\n"; }}, $rootdir);
The output I get from this is:
file:file1.xml
dir:testdir
size1:
size2:
date:
file:file2.xml
dir:testdir\folder1
size1:
size2:
date:

Replies are listed 'Best First'.
•Re: getting file size and date
by merlyn (Sage) on Sep 17, 2002 at 21:33 UTC
    I'm not exactly sure what you're doing with these lines:
    $file =~ s/$dir\///g; $dir =~ s/\//\\/g;
    If you could talk those through in English, I might be able to help.

    However, if your intent is to get just the basename, be aware that $_ already has that. Simplifying your code, I'd just go with this:

    find sub { return unless -f; my $size = -s; print "file: $_\n", "dir: $File::Find::dir\n", "size: $size\n"; }, $rootdir;

    -- Randal L. Schwartz, Perl hacker

Re: getting file size and date
by mojotoad (Monsignor) on Sep 17, 2002 at 22:57 UTC
    Consider using the built in cache for stat operations, '_'. The initial -f populates the cache. Like so (I have made no attempt to optimize your code...consider merlyn's advice, but add in a date capture:

    #!/usr/bin/perl use File::Find; $rootdir = "testdir"; find(sub { if (-f) { $file = $File::Find::name; $dir = $File::Find::dir; ($size,$date) = (stat _)[7,9]; $sz = -s _; $file =~ s/$dir\///g; $dir =~ s/\//\\/g; print "file:$file\ndir:$dir\nsize1:$size\nsize2:$sz\ndate:$date\n"; }}, $rootdir);

    Matt

Re: getting file size and date
by Galen (Beadle) on Sep 17, 2002 at 22:53 UTC
    Thanks that does work for me. The two lines you mentioned were for formatting output (I do some additional things). Apparently I wasn't hitting the file correctly - but $_ is the right way to do it. I appreciate you help very much.