如何在Perl中获取文件的上次修改时间?

cow*_*god 63 perl file-io

假设我有一个文件句柄$fh.我可以检查它的存在-e $fh或其文件大小-s $fh一些关于该文件的其他信息.如何获得最后修改的时间戳?

cow*_*god 97

您可以使用内置模块File::stat(包含自Perl 5.004).

调用stat($fh)返回一个数组,其中包含有关传入的文件句柄的以下信息(来自perlfunc手册页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
Run Code Online (Sandbox Code Playgroud)

此数组中的元素编号9将为您提供自纪元以来的最后修改时间(格林尼治标准时间1970年1月1日00:00).从那里你可以确定当地时间:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);
Run Code Online (Sandbox Code Playgroud)

为了避免前一个例子中需要的幻数 9,另外使用Time::localtime另一个内置模块(也包括Perl 5.004).这需要一些(可以说)更易读的代码:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);
Run Code Online (Sandbox Code Playgroud)


Mic*_*man 24

使用builtin stat函数.或者更具体地说:

my $modtime = (stat($fh))[9]
Run Code Online (Sandbox Code Playgroud)


Dav*_*nds 18

my @array = stat($filehandle);
Run Code Online (Sandbox Code Playgroud)

修改时间以Unix格式存储在$ array [9]中.

或明确:

my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
    $atime, $mtime, $ctime, $blksize, $blocks) = stat($filepath);

  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 in seconds since the epoch
  9 mtime    Last modify time in seconds since the epoch
 10 ctime    inode change time in seconds since the epoch
 11 blksize  Preferred block size for file system I/O
 12 blocks   Actual number of blocks allocated
Run Code Online (Sandbox Code Playgroud)

该时代是格林尼治标准时间1970年1月1日00:00.

更多信息在stat.


Pau*_*ham 13

您需要stat调用和文件名:

my $last_mod_time = (stat ($file))[9];
Run Code Online (Sandbox Code Playgroud)

Perl也有不同的版本:

my $last_mod_time = -M $file;
Run Code Online (Sandbox Code Playgroud)

但该值与程序启动时相关.这对排序等问题很有用,但您可能需要第一个版本.


小智 9

如果你只是比较两个文件,看看哪个更新,那么-C应该工作:

if (-C "file1.txt" > -C "file2.txt") {
{
    /* Update */
}
Run Code Online (Sandbox Code Playgroud)

还有-M,但我认为这不是你想要的.幸运的是,通过Google搜索这些文件操作符的文档几乎是不可能的.

  • 要谷歌`-M`,添加引号"-M",因为`-X`删除了具有'X`的结果......顺便说一下,'-M'是OP想要的. (2认同)