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

I am new to perl and trying to get a handle on things. Although I have seen code that does what I want I am interested in knowing why this does not work as I expect.

I have the current directory set to C: in the command prompt and am trying the simple code below with two different results.

The first line uses opendir dirs, '.' to get the files in the current directory and the second line uses opendir dirs2, 'C:\\' to do the same. I then compare them on the third line and get a return value of 1 telling me that they are the same.

In the while loop I loop through all the files and only print the ones that are tested true with -d $_. This works fine until I replace dirs with dirs2 and run the same code. Nothing is returned this time because -d $_ this time is returning a value of 0. If both dirs and dirs2 are the same why does the while loop work with one but not the other?

opendir dirs, '.' or die "Couldn't open current directory: $!"; opendir dirs2, 'C:\\' or die "Couldn't open current directory: $!"; print dirs == dirs2, "\n"; while ($_ = (readdir dirs)) { print $_, "\n"; if (-d $_) { print "This is a dir $_ \n"; } }

janitored by ybiC: Add balanced <readmore> tags and <p>aragraphs

Replies are listed 'Best First'.
Re: Reading directories
by Beechbone (Friar) on Sep 23, 2003 at 13:21 UTC
    I tested your code and it works fine here, regardless wether I readdir() from "dirs" or "dirs2". Are you sure this is the problematic code? And, are you sure you are really in "C:/"?

    But, there is really a problem with that code:

    use warnings; use warnings; use warnings;

    If you had, you would have notived this:

    Argument "dirs2" isn't numeric in numeric eq (==) at - line 3. Argument "dirs" isn't numeric in numeric eq (==) at - line 3.
    In clear English: You cannot do a numerical comparision on directory handles. In fact, you cannot numerical compare anything else but numbers...

    Another problem is your semantics if you use "dirs2". You read the content from some directory you opened ("C:/") but you test if that content exists in the current directory ("-d $_"). Always append the correct directory, e.g. "-d 'C:\\' . $_"

    BTW: You should really use UPPERcase directory handle names---the lowercase ones give nasty warnings.