file date comparison in perl
This is a little sample code that shows how to compare the last-modified time for one file with that of another in Perl:
Output is "/home/wereldmuis/oldfile is older than /home/wereldmuis/newfile".
#!/usr/bin/perl
use strict;
use warnings;
my $ofile = "/home/wereldmuis/oldfile";
my $nfile = "/home/wereldmuis/newfile";
open(FO, $ofile);
open(FN, $nfile);
my @info = stat FO;
my $oftime = $info[8]; # file modification time in epoch seconds
@info = stat FN;
my $nftime = $info[8];
my $current = time(); # current time in epoch seconds, just an example
if ($nftime < $oftime){
print "$nfile is older than $ofile\n";
} else {
print "$ofile is older than $nfile\n";
}
Output is "/home/wereldmuis/oldfile is older than /home/wereldmuis/newfile".
2 Comments:
This is very awkward; look up file test functions (man perlfunc):
#! /usr/bin/perl
my $f1 = shift;
my $f2 = shift;
my $cmp = (-M $f1 < -M $f2);
my $newer = $cmp ? $f1 : $f2;
my $older = $cmp ? $f2 : $f1;
print "$newer is newer than $older\n";
I never claimed to be a perl expert, though!
I haven't even worked with perl in a couple of years. But that's nice to know if I ever need it again. Hopefully it will help someone else.
Post a Comment
<< Home