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

Hi monks. I want to make a program that reads a directory looking for subdirectories. It look like this :

opendir($dh,"C:/"); while($var = readdir($dh)){ if(-d $var){ print "$var\n"; } } close $fh;

I was expecting to get a list with the foldernames Can someone explain why this example is not working? According to a source on the internet this looks ok, hope you can help me. tx.

Replies are listed 'Best First'.
Re: read directory
by choroba (Cardinal) on Dec 20, 2017 at 15:32 UTC
    This has been asked many times. Even the documentation of readdir itself mentions the problem:
    If you're planning to filetest the return values out of a readdir, you'd better prepend the directory in question.

    Also, you should always check the return value of opendir. Moreover, use strict and warnings, they should tell you that $fh and $dh are different variables.

    So, all of that together:

    #!/usr/bin/perl use warnings; use strict; my $dir = 'C:/'; opendir my $dh, $dir or die $!; while (my $file = readdir $dh) { print "$file\n" if -d "$dir/$file"; } close $dh;

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      Why doesn't my if-statement work?

        OK, let's assume you start in "D:\Program Files" and run the script. It reads a filename from C:\, let's say temp. Your if tries to verify that the directory temp exists in the current directory, i.e. "D:\Program Files\temp" is a directory, which is false. My if, on the other hand, tries to verify that "C:\temp" is a directory, which is true.

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: read directory
by hippo (Archbishop) on Dec 20, 2017 at 16:07 UTC
    According to a source on the internet this looks ok

    Please provide details of the "source on the internet" so that we might prevent further spread of this misconception. Thanks.

      Forgive me my ignorance, English is not my native language.

        Simply: where on the internet did you find the code in your first post? A URL would be great. Thanks.

Re: read directory (readdir is raw eggs)
by Anonymous Monk on Dec 21, 2017 at 01:19 UTC

    Hi,

    readdir is raw eggs, what you want is cake ( Path::Tiny or Win32::Unicode )

    #!/usr/bin/perl -- use strict; use warnings; use Path::Tiny qw/ path /; my @files_dirs = path( "C:/" )->children; my @files = grep { $_->is_file } @files_dirs; my @dirs = grep { $_->is_dir } @files_dirs; ...

    #!/usr/bin/perl -- use strict; use warnings; use Win32::Unicode ; my @files = file_list( 'C:/' ); my @dirs = dir_list( 'C:/' ); ...