在这里,我使用存储在本地目录中的last_run文件,如果它不等于当前的日期时间,就更新它的最后修改日期。是否有可能不将符号写入文件,而是以其他方式更新mtime?
我看到有一个模块File::Touch,但我不想使用它,因为我已经打开了一个文件,而且使用文件描述符的速度会更快。
#!/usr/bin/perl
use utf8;
use strict;
use warnings;
use File::stat;
use DateTime;
my $file_name = "last_run";
if (-e $file_name)
{
my $fh;
if (open($fh, "+<", $file_name))
{
my $timestamp = stat($fh)->mtime;
my $now = DateTime->now(time_zone => 'local');
my ($sec, $min, $hour, $day, $month, $year) = localtime($timestamp);
$month += 1;
$year += 1900;
if ($now->day != $day or $now->month != $month or $now->year != $year)
{
print $fh ' '; # <- I have to write something into the file
}
print "$day $month $year\n";
print $now->day.' '.$now->month.' '.$now->year."\n";
}
else
{
print "cannot open +< $file_name: $!";
}
close($fh);
}
else
{
open(my $fh, ">", $file_name)
or print "cannot open > file name: $!";
}发布于 2020-11-11 07:45:16
您正在寻找utime函数。
文件中的一些引文:
更改文件列表中每个文件的访问和修改时间。列表的前两个元素必须是按该顺序进行的数字访问和修改时间。返回成功更改的文件数。每个文件的inode更改时间设置为当前时间。从Perl5.8.0开始,如果列表的前两个元素是undef,则调用C库中的
utime(2)syscall时使用一个空的第二个参数。在大多数系统上,这将将文件的访问和修改时间设置为当前时间。在支持futimes(2)的系统上,您可以在文件之间传递文件句柄。在不支持futimes(2)的系统上,传递文件句柄会引发异常。文件句柄必须作为全局引用或glob引用传递,才能被识别;裸单词被认为是文件名。
所以,就像:
utime undef, undef, $fh;将文件的修改(和访问)时间更新到当前文件。如果您没有使用大多数系统,那么文档中还有另一个显式使用当前时间的例子。
futimes(2)出现在Linux和BSD上。如果您使用的是不同的操作系统,则必须使用文件名而不是句柄。
https://stackoverflow.com/questions/64782173
复制相似问题