0

How to skipp . and .. directories in DirHandle?

use DirHandle;
if (defined $d) {
    while (defined($_ = $d->read)) { print "$_ \n" ; }
 undef $d;
}
Chetu
  • 29
  • 3

1 Answers1

5

By the way, don't use undef $d$d = undef is preferable.

There are several ways — all of them simple if you know Perl or regular expressions

The obvious

while ( defined(my $node  = $d->read) ) {
  next if $node eq '.' or $node eq '..';
  print "$dir\n"; 
}

Using a regex

while ( defined(my $node  = $d->read) ) {
  next if $node =~ /\A\.\.?\z/;
  print "$dir\n"; 
}

or, more tidily but less safely because a Linux directory node can have names like ... and .... etc., you can just ensure that the node contains something other than a dot .

while ( defined(my $node  = $d->read) ) {
  next unless $node =~ /[^.]/;
  print "$dir\n"; 
}
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • 4
    To expand on Borodin's comment, `$d = undef;` sets the var to undefined, while `undef $d;` also frees some memory associated with the scalar, making it more expensive to use that variable again. – ikegami Apr 15 '15 at 13:51