Modifying a File Without Changing Its Timestamp
Your file system keeps track of when each file was last modified. But have you ever wanted to edit a file without affecting its timestamp? Using the "utime" function, which is built in to Perl, you can! Here’s how:
- Record the old timestamp. Timestamps are stored as the number of seconds since January 1, 1970 00:00 GMT. The stat() function returns the existing timestamp (among other things):
($dev,$ino,$mode,$nlink,$uid,$gid, $rdev,$size,$atime,$mtime,$ctime, $blksize,$blocks) = stat($filename);Here, "$mtime" is the one you want. You could get just that value by selecting an element from the stat() array:
$mtime = (stat($filename))[9];
- Modify the file using Perl’s file I/O functions, then close the file handle.
- Reset the timestamp to the value stored in "$mtime" with the utime() function:
utime $mtime, $mtime, $file or die "Error setting timestamp for $file: $!n";Note: the $mtime value is listed twice here, because you can also use utime() to set the last-accessed time of the file (this has no effect on Windows filesystems, which don’t maintain an access time attribute). If you want to set them to different values, use this variant:
utime $atime, $mtime, $file or die "Error setting timestamp for $file: $!n";

You’ve mentioned windows systems don’t keep track of access times for the native file system, this is not true, infact by default access times are tracked but in certain configurations this can be turned off to speed up file system access.
The -A file test operator returns the access time.
this dir command list access times
perl -le “print `dir /TA`”
–Shalom
perl -e ‘$,=$”,$_=(split/\W/,$^X)[y[eval]]]+–$_],print+just,another,split,hack’er
Comment by anonymous — December 1, 2006 @ 3:13 pm
You’re right. It’s the “change” permission that Windows systems don’t track. I realized that just the other day when teaching a class, in fact. I had forgotten that I had posted that here though.
Comment by William Ward — December 1, 2006 @ 3:26 pm
The change permission isn’t allowed in Windows do to how Perl requests access to file handles. This problem is solved with the module Win32API::File::Time on CPAN.
Comment by Mike Gent — January 25, 2007 @ 3:36 pm
Thanks Mike.
Comment by William Ward — January 25, 2007 @ 3:46 pm