Henrik Henrik - 3 months ago 10
Linux Question

Getting the whole dirent structure in perl

The

readdir
syscall on linux returns a
dirent
structure that contains more information that just the file name, but it seems perl's
readdir
only returns the name (I've tried assigning it to a variable and using
Data::Dumper::dumper
on that to see if it was just something that stringifies to the filename - I don't know if that is a useable way to do that, but it was the best I could think of). Is there any way to get the other information (specifically I need the
d_type
), without
stat
'ing the name?

Answer

You can use IO::Dirent:

use strict;
use warnings 'all';
use 5.010;

use IO::Dirent qw(:ALL); # import constants DT_REG, DT_LNK, etc.

my %types = (
    DT_REG() => 'regular file',
    DT_LNK() => 'symbolic link',
    DT_DIR() => 'directory'
);

my $dir = 'foo';
opendir my $dh, $dir or die "Failed to opendir '$dir': $!";

while (my $entry = nextdirent($dh)) {
    say join "\t", $entry->{name}, $types{ $entry->{type} };
}

Output:

..      directory
baz     symbolic link
.       directory
bar     regular file