Search code examples
perlstat

What are the semantics of 'stat' on a dirhandle in Perl?


On researching another question I noted that the stat function in Perl can take a dirhandle as its argument (instead of a filehandle or filename).

However I can't find any examples of correct use of this - there are none in the Perl manual.

Can anyone show an example of how to use it?


Solution

  • You use it in the same way you do for a file or filehandle:

    #!/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";
    

    The ability to use stat on directory handles was just added around Perl 5.10 so it should be avoided if you care about portability.