How do you ‘touch’ a file in Perl? utime. No, not “you time”. utime.

my $access_time = $modified_time = time;
utime $access_time, $modified_time, "filename";

With Perl 5.7.2 and later, you can pass undef for the first two parameters to set them to the current time:

utime undef, undef, "filename";

For files on a NFS server, this becomes the time of the NFS server, not the local computer’s time, so beware.

Unlike the touch utility, it will not create a zero-length file if one didn’t already exist.

So, don’t be evil, but you can also do this:

my $ts = time - 360;  # now minus 1 hour
utime $ts, $ts, @files_i_want_to_backdate;

Oh and you must have write access to the file to be able to adjust these timestamps.

The utime function will return the number of files that it updated. If it returns 0, or some number you did not expect, inspect the $! variable for the reason (typically permission denied, or file not found).

Of course, you could have learned all this by using perldoc -f utime, but I’m doing my part to help you justify reading personal blogs while at work.


TrackBack URL for this entry:


This article was published on August 12, 2006 7:16 PM.

The article previously posted was OSCON: Perl Hacks you Never Knew Existed.

The next article is ack.

Many more can be found on the home page or by looking through the archives.

Powered by Movable Type