【问题标题】:What are the semantics of 'stat' on a dirhandle in Perl?Perl 中 dirhandle 上的“stat”的语义是什么?
【发布时间】:2008-11-30 15:20:01
【问题描述】:

在研究另一个问题时,我注意到 Perl 中的 stat 函数可以将 dirhandle 作为其参数(而不是文件句柄或文件名)。

但是我找不到任何正确使用它的示例 - Perl 手册中没有。

谁能举例说明如何使用它?

【问题讨论】:

    标签: perl stat


    【解决方案1】:

    您使用它的方式与对文件或文件句柄的使用方式相同:

    #!/usr/bin/perl
    use strict;
    
    my $dir = shift;
    opendir(DIR, $dir) or die "Failed to open $dir: $!\n";
    my @stats = stat DIR;
    closedir(DIR);
    my $atime = scalar localtime $stats[8];
    
    print "Last access time on $dir: $atime\n";
    

    在 Perl 5.10 中刚刚添加了在目录句柄上使用 stat 的功能,因此如果您关心可移植性,应该避免使用它。

    【讨论】:

    • 所以它只是 stats() 目录本身,与 readdir() 没有任何关系?
    • @Alnitak:没错,它与“stat $dir”相同,就像“stat FILEHANDLE”与“stat $file”相同。
    【解决方案2】:

    您可以像在文件句柄上使用 stat 一样使用它:

    <~> $ mkdir -v foo ; perl -e 'opendir($dh , "./foo"); @s = stat $dh; print "@s"'
    mkdir: created directory `foo'
    2049 11681802 16877 2 1001 1001 0 4096 1228059876 1228059876 1228059876 4096 8
    

    (就我个人而言,我喜欢使用 File::stat 来获得好的命名访问器,这样我就不必记住(或查找)第五个元素是 UID...)

    【讨论】:

      【解决方案3】:

      请注意,如果句柄曾经用作文件句柄和目录句柄,则统计信息将应用于文件,而不是目录:

      $ perl -wl
      opendir $h, "." or die;
      open $h, "/etc/services" or die;
      print "dir:".readdir($h);
      print "file:".readline($h);
      print stat("/etc/services");
      print stat(".");
      print stat($h);
      close($h);
      print stat($h);
      __END__
      dir:.
      file:# Network services, Internet style
      
      205527886633188100018274122800783211967194861209994037409640
      20551515522168777410001000020480122803711512280371021228037102409640
      205527886633188100018274122800783211967194861209994037409640
      stat() on closed filehandle $h at - line 1.
          (Are you trying to call stat() on dirhandle $h?)
      

      【讨论】:

        【解决方案4】:

        我在 Windows (ActivePerl) 上使用 Perl 5.10.1,但在 dirhandle 上执行 stat 不起作用。但是对目录的路径字符串进行统计是有效的。

        作品

          my $mtime = (stat( $directory ))[ 9 ];
          print "D $directory $mtime\n";
        

        这没有(“dirfd 函数未实现...”)

          my $dh;
          if( opendir( $dh, $directory ) == 0 ) {
            print "ERROR: can't open directory '$directory': $!\n";
            return;
          }
          $mtime = (stat( $dh ))[ 9 ];
          print "D $directory $mtime\n";
        

        【讨论】:

          猜你喜欢
          • 2017-02-26
          • 2011-06-01
          • 2019-06-13
          • 1970-01-01
          • 1970-01-01
          • 2013-06-08
          • 2019-12-28
          • 2020-04-25
          • 2013-04-26
          相关资源
          最近更新 更多