假设我有一个文件句柄$fh
。我可以使用 -e $fh
检查它的存在,或者使用 -s $fh
或 a slew of additional information about the file 检查它的文件大小。 。如何获取其最后修改的时间戳?
最佳答案
调用内置函数 stat($fh)
返回一个数组,其中包含有关传入的文件句柄的以下信息(来自 perlfunc man page for stat
):
0 dev device number of filesystem
1 ino inode number
2 mode file mode (type and permissions)
3 nlink number of (hard) links to the file
4 uid numeric user ID of file's owner
5 gid numeric group ID of file's owner
6 rdev the device identifier (special files only)
7 size total size of file, in bytes
8 atime last access time since the epoch
9 mtime last modify time since the epoch
10 ctime inode change time (NOT creation time!) since the epoch
11 blksize preferred block size for file system I/O
12 blocks actual number of blocks allocated
此数组中的第 9 个元素将为您提供自该纪元以来的最后修改时间(1970 年 1 月 1 日 00:00 GMT)。由此您可以确定本地时间:
my $epoch_timestamp = (stat($fh))[9];
my $timestamp = localtime($epoch_timestamp);
或者,您可以使用内置模块 File::stat
(从 Perl 5.004 开始包含)以获得更加面向对象的界面。
为了避免上一个示例中所需的魔数(Magic Number) 9,请另外使用另一个内置模块Time::localtime
(从 Perl 5.004 开始也包含在内) 。这些共同导致了一些(可以说)更清晰的代码:
use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);
关于perl - 在 Perl 中如何获取文件的最后修改时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/509576/