The_Last_Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow monks. I am having a problem with the stat function returning an empty list. Basically i have a directory of files that i need to get data from. So the directory is called Language and has a bunch of text files called French.txt, Spanish.txt etc. Here is the code:
opendir(DIR,$dir) or die "dead"; @textfiles = readdir DIR; foreach(@textfiles){ @data = stat($_); if(scalar(@data) == 0) { print "Has no items"; } print "$_\n"; }
It always prints the "Has no items" and then proceeds to print fhe file name like French.txt and Spanish.txt. Am i doing something wrong? I also tried looping through the data array and printing stuff but it ended up not printing anything

Replies are listed 'Best First'.
Re: Stat function returning an empty list
by Paladin (Vicar) on Mar 06, 2015 at 21:08 UTC
    readdir doesn't return the path to the file, just the file name. You have a file called "Language/French.txt" but are statting just "French.txt". Change your stat call to:
    stat("dir/$_");
      You, Mr.Paladin, are a saviour :)
Re: Stat function returning an empty list
by Discipulus (Canon) on Mar 06, 2015 at 21:21 UTC
    first and always use strict and warnings, and the more powerful debbuging tool i know: print..
    as in the following oneliner:
    perl -e "opendir my $dir,'.' or die; while ($_ = readdir $dir){@stat = + stat $_; print qq([$_]@stat\n)}"
    You must have some problem with $dir, because your posted code, with '.' as value of $dir never print to me "Has no items"

    HtH
    L*
    PS warning if you are on windows stat has some caveats that i dont rememer now.. maybe the module override the built-in or something else

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Stat function returning an empty list (path/tiny)
by Anonymous Monk on Mar 06, 2015 at 22:04 UTC
    use Path::Tiny it readdirs for you so you don't have to trip The_Last_Monk :) it even takes care of dots directories, and even takes regex to filter names
    use Path::Tiny qw/ path /; my @textfiles = path( $dir )->children( qr/\.txt$/i );

      File::Find has the ability to not visit any subdirectories via preprocess option if follow* options are false. (Else, all the files would have to be iterated over in a directory only to skip them all.) Does Path::Tiny not have that? While browsing the P::T code I had a smidgen of hope as the (directory) search is hand written, but did not find anything relevant.

Re: Stat function returning an empty list
by Anonymous Monk on Mar 06, 2015 at 21:41 UTC

    I'm a little surprised that the stat docs don't mention this, but the $! variable contains the error. Which in your case would most likely be "No such file or directory". So you could say something like if(!@data) { warn "stat $_ failed: $!" } else { ... }