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

opendir(DIR, $dirname) || die "can't opendir $dirname': $!"; @dots = readdir(DIR); closedir DIR; foreach $file (@dots){ my $diff = -M $file; print "The age is" .int($diff)."\n"; }
The above code doesnot give the age for the directory. It shows as 0 always. How can we find the age of both file and directory

Replies are listed 'Best First'.
Re: Age of directory
by Corion (Patriarch) on Mar 17, 2009 at 12:03 UTC

    Print out the filename and think about whether the file can be found that way. readdir does not return the filename together with the directory in which the file was found.

Re: Age of directory
by ig (Vicar) on Mar 18, 2009 at 03:57 UTC

    From perlfunc:

    -M Script start time minus file modification time, in days.

    Note the units: days

    You print the integer portion of $diff: int($diff), so unless it has been more than one day since the directory was modified, your result will be 0.

    To see that -M is returning a non-zero result, try your program without the int(). You might try the following:

    #!/usr/bin/perl use warnings; use strict; my $dirname = "."; opendir(DIR, $dirname) || die "can't opendir $dirname': $!"; my @dots = readdir(DIR); closedir DIR; foreach my $file (@dots){ my $diff = -M $file; print "The age of $file is $diff : " . $diff . " : " . int($diff) +. "\n"; }
      Thanks for the reply. The age of the directory is displayed only for "." and "..". For the rest of the files it and subdirectories it displays as 0. How can I print the age of all files and subdirectories within a directory

        The script in my previous post prints non-zero times for all files and directories in the current directory when I run it on my system.

        If you are running the same script and getting times of zero for everything other than "." and "..", then something quite strange is happening. I suggest you post the script you are running (the whole script, not part of it and remember to use code tags so we can read it), a sample of the output you get on your system and details of your system including operating system, version, perl distribution and version.