Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

comparing files based on timestamps

by Anonymous Monk
on Apr 02, 2009 at 07:25 UTC ( [id://754879] : perlquestion . print w/replies, xml ) Need Help??

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

Hi, I have a folder which contains 4 sub folders . how can i know which folder is the latest one based on the timestamps. How to read the timestamps of a file or a folder in perl .Do i need to use any perl module or standard perl is enough. ex : folder subfolder1 subfolder2

Replies are listed 'Best First'.
Re: comparing files based on timestamps
by Crian (Curate) on Apr 02, 2009 at 07:31 UTC
    perldoc -f stat

    could be what you are searching for.

Re: comparing files based on timestamps
by manoj_speed (Prior) on Apr 02, 2009 at 07:43 UTC

    Using stat() function we can get it.

    Let's try this example,

    #! /bin/perl
    use strict;
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$ctime,$blksize,$blocks) = stat("subfolder1");
    print "$atime\t$mtime\t$ctime\n";

    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat("Library");
    print "$atime\t$mtime\t$ctime\n";

    For more details see "perldoc -f stat".

Re: comparing files based on timestamps
by imrags (Monk) on Apr 02, 2009 at 07:40 UTC
    Well, if you want, you can put this code in a loop
    scalar localtime((stat("$dir_name/$file"))[9]);
    and start comparing files
      This is a very good idea. item 9 from the list slice is the mtime. This line will produce something like:
      Mon Nov 12 23:21:31 2007. If you want to get some numbers to make comparison easier, continue using list slice like this:
      (my $m_time) = (stat($source_path))[9]; my ($i_wday, $i_month, $day, $year) = (localtime($m_time))[6,4,3,5];
      Only create the variables of interest to you. If you don't need the day of week, then don't use index 6. Note that months will wind up being 0-11 and year is real year-1900. Also note that the slice values don't have to be in order. I organize the lvalues then figure out the order of the slice values. It is not possible for the slice values in ".." sequence to go backwards 4..6 works but 6..4 doesn't work, at least with the versions of Perl I use.

      Update: I would keep the values as UTC rather than localtime like above use gmtime. Strangely enough if I remember right, gmtime and timegm are in Time::Local; so if my memory is right, watch out for that!

      Little tired today but also consider converting to epoch seconds.

      #remember for timegm month[0-11] and year is delta from 1900 my $time = timegm(0,$minutes,$hours,$days,$month-1,$year-1900); print "epoch seconds $time\n";
      This gives a single integer value that is easily compared.