Search code examples
perlstatopendir

Perl, Reading dir and getting stat() for each file


In Perl, When I'm trying to read dir in a loop, and perform for each file stat() in order to get $size and $mode, I get wrong data!

For example, I just created simple text file and it shows me it has permission 0000 and no size.

Perl Code:

if (!@ARGV[0]) {
    die("Za mało parametrów!\n");
}

$dirname = @ARGV[0];

opendir(DIR, $dirname) || die("Nie mogę otworzyć katalogu!\n");
while( $filename = readdir(DIR) ) {

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

    $perm = sprintf("%04o", $mode & 07777);
    $tmp1 = int(($size/1024));
    $tmp2 = length($filename);

    if (($tmp1 > $tmp2) && ($perm =~ /.[^5410]../)) {
        print("$filename\n");
    }
}
closedir(DIR);

Solution

  • You will need to pass the full filepath to the stat() function. At the moment you are just passing a filename, so the script will look in its current directory for this file.

    In other words, do this:

    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
             $atime,$mtime,$ctime,$blksize,$blocks) = stat("$dirname/$filename");