On Oct 5, 7:50 am, [EMAIL PROTECTED] (Jeff Pang) wrote:
> 2007/10/5, [EMAIL PROTECTED]
> <[EMAIL PROTECTED]>:
>
> > I would like to compare two files by comparing the files dates.
> > If one file shows
> > ls -la May 12 2003 filename
> > and the other name shows the same date they are OK for me (I'm not
> > interested in the time part only the date of the file)
> > But if the dates are not the same I would like to copy one of the
> > files.
> > How do I do this in Perl?
> if ( int(-M "file1.txt") != int(-M "file2.txt") ) {
> # copy the file
> }
That's a very naïve approach that will frequently fail.
For example:
File one modified 10/1/2007 9am
File two modified 10/1/2007 3pm
and the current time is 10/2/2007 12pm
-M 'file1' will return 1.125
-M 'file2' will return 0.875.
int(1.25) == 1
int(0.875) == 0
There are two possible "correct" solutions. One is to actually
execute `ls -l` for each file and parse the output. The other is to
take the return values of the -M calls, subtract them from the current
unix time stamp, convert both times to date strings, and then compare
the dates. For example:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw/strftime/;
my $date1 = m_to_date(-M 'file1.txt');
my $date2 = m_to_date(-M 'file2.txt');
if ($date1 eq $date2) {
# copy the file
}
sub m_to_date {
my $days_ago = shift;
my $ts = time() - ($days_ago * 24 * 60 * 60);
my $date = strftime('%Y-%m-%d', localtime($ts));
return $date;
}
__END__
Paul Lalli
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/