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

my directory holds another directory name "p17" and I am doing following to read that directory,
my @a; my $dir = "/and/evel/aap/list/60"; opendir(PATCH, $dir) || die "Unable to open $dir "; @a = readdir(PATCH); print "@a\n"; closedir(PATCH); exit;
After running above code I am getting following values in @a (array), 0 '.' 1 '..' 2 'p17' but I am suppose to get just p17, Have I done any thing wrong, can any one suggest me how can I get just another directory(p17)name???

Replies are listed 'Best First'.
Re: Reading Directory
by moritz (Cardinal) on Jul 14, 2009 at 08:03 UTC
    On Unix, every directory contains the directory . which is a reference to itself, and .., which is a reference to the parent directory. If you don't want to consider those, filter them out from the array.

    (Note that "reference" is a bit vague, I think it's more like a hard link, but I'm not entirely sure).

      See a tutorial I just ran across, especially section 6.1.1.3 and 6.1.3. It seems to be a reasonable description.

      --MidLifeXis

      The tomes, scrolls etc are dusty because they reside in a dusty old house, not because they're unused. --hangon in this post

Re: Reading Directory
by ELISHEVA (Prior) on Jul 14, 2009 at 08:44 UTC

    Take a look at File::Spec's no_upwards method. It lets you (portably) skip the dot directories:

    use strict; use warnings; use File::Spec; my @x; opendir(DIR, $dir) or die "Can't open directory $dir: $!"; eval { @x = File::Spec->no_upwards(readdir(DIR)); }; closedir(DIR); print "@x\n";

    Best, beth

Re: Reading Directory
by Anonymous Monk on Jul 14, 2009 at 08:00 UTC
Re: Reading Directory
by tokpela (Chaplain) on Jul 14, 2009 at 09:25 UTC

    I would also add that for scalability you should always iterate over a directory as opposed to pushing all of the filenames into an array.

    I would also use a lexical directory handle.

    my $dir = "/and/evel/aap/list/60"; opendir(my $d, $dir) || die "Unable to open $dir "; while (my $filename = readdir($d)) { # removes . and .. next if ($filename =~ /^\.+$/); my $filepath = "$dir/$filename"; ..... } closedir($d);
Re: Reading Directory
by ropey (Hermit) on Jul 14, 2009 at 11:10 UTC

    Or use grep to filter the directory

    @a = grep {$_ !~ /^\.{1,2}$/} readdir(PATCH);
      Hi there your grep seems to work but can you make me understand how?, I am not getting this "!~" business. suggestion please, Cheers
        I am not getting this "!~" business
        From Binding Operators:
        Binary "!~" is just like "=~" except the return value is negated in the logical sense.