如何在Perl中获取文件的最后修改时间? [英] How do I get a file's last modified time in Perl?

查看:778
本文介绍了如何在Perl中获取文件的最后修改时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文件句柄 $ fh 。我可以使用 -e $ fh 或其文件大小检查它的存在与 -s $ fh 关于文件的大量附加信息。我怎样才能得到它的最后修改时间戳?

解决方案

您可以使用内置模块 :: stat (包含在Perl 5.004中)。
$ b

调用 stat($ fh)返回一个数组,其中包含有关传入的文件句柄的信息(来自 stat ):

  0 dev文件系统的设备编号
1 ino inode编号
2模式文件模式(类型和权限)
3链接到文件的(硬)链接数
4 uid数字文件所有者的用户ID
5 gid数字组文件所有者的ID
6 rdev设备标识符(仅用于特殊文件)
文件总大小(以字节为单位)
8 atime自上个世纪以来的上次访问时间
9上次自上一次修改以来的修改时间
10 ctime inode chang e时间(非创建时间!)
11 blksize文件系统I / O的首选块大小
12块实际分配的块数

这个数组中的第九个元素会给你从历元开始的最后修改时间( 00:00 January 01,1970 GMT )。从那你可以确定当地时间:

pre $ my $ epoch_timestamp =(stat($ fh))[9];
my $ timestamp = localtime($ epoch_timestamp);

为了避免前面例子中需要的 magic number Time :: localtime ,另一个内置模块(也包括在Perl 5.004之内)。这需要一些(可以说)更清晰的代码:

 使用File :: stat; 
使用Time :: localtime;
my $ timestamp = ctime(stat($ fh) - > mtime);


Suppose I have a filehandle $fh. I can check its existence with -e $fh or its file size with -s $fh or a slew of additional information about the file. How can I get its last modified time stamp?

解决方案

You can use the built-in module File::stat (included as of Perl 5.004).

Calling stat($fh) returns an array with the following information about the file handle passed in (from the 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

The 9th element in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);

To avoid the magic number 9 needed in the previous example, additionally use Time::localtime, another built-in module (also included as of Perl 5.004). This requires some (arguably) more legible code:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);

这篇关于如何在Perl中获取文件的最后修改时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆