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

Hi, Howcome the following simple piece of code doesn't return all the files in the directory? All it returns is the single "." directory?
#!/usr/bin/perl opendir (ID, "/home/actionet/gallerymain") || print "Couldn't open dir +ectory for reading\n"; (@dir0) = readdir(ID) || print "Couldn't read directory contents.\n"; closedir(ID) || print "Couldn't close directory after reading contents +\n"; foreach $inode0 (@dir0) { print "File about to be processed is: $inode0\n"; next if ($inode0) =~ /^\./; $thefile = "/home/actionet/gallerymain" . $inode0; next if (-d $thefile); print "File to process is: $thefile\n"; }

Replies are listed 'Best First'.
Re: readdir fails?
by Juerd (Abbot) on Mar 03, 2002 at 00:45 UTC

    (@dir0) = readdir(ID) || print "Couldn't read directory contents.\n";

    || forces scalar context. Your code actually is:
    @dir0 = (readdir(ID) || 1); # assuming print doesn't fail
    What you probably want, is:
    (@dir0 = readdir(ID)) || print "...";
    which is equal to:
    @dir0 = readdir(ID) or print "...";
    (|| and or are not equal: || is tighter (see perlop).)

    Update (20020303021949)
    In my chatterbox nodelet, I read: crazyinsomniac says readdir fails? mention of -MO=Deparse couldn't hurt ;)
    So here it is:
    2;0 juerd@ouranos:~$ perl -MO=Deparse,-p -e'(@dir) = readdir(ID) || pr +int "X"' (@dir = (readdir(ID) || print('X'))); -e syntax OK

    The -p adds extra parens. Documentation can be found at B::Deparse.

    ++ vs lbh qrpbqrq guvf hfvat n ge va Crey :)
    Nabgure bar vs lbh qvq fb jvgubhg ernqvat n znahny svefg.
    -- vs lbh hfrq OFQ pnrfne ;)
        - Whreq
    

•Re: readdir fails?
by merlyn (Sage) on Mar 03, 2002 at 02:56 UTC
      ++merlyn ... And can be implemented much nicer and more cross-platform friendly with File::Spec ...

      use File::Spec; my $thefile = File::Spec->catfile('home', 'actionet', 'gallerymain', $ +inode0); next if -d $thefile;

       

      perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

Re: readdir fails?
by webadept (Pilgrim) on Mar 03, 2002 at 04:20 UTC
    My understanding (limited as it is) says that readdir is like reading and array and you need a loop in there to get anything past the . or .. or anything else. Try something like this.
    opendir(DIR, $dirname) || die "Horrible Death"; while(defined($file=readdir(DIR)) { print $file, "\n"; } closedir(DIR);
    This gets you through all the files in the directory.

    Hope that helps out.

    webadept.net