You can use rewinddir. Given a directory dirA containing fileA to fileE the script below goes through the directory until it reaches and unlinks dirA/fileB then does a rewinddir then shows directory contents again. Note that fileB no longer appears.
use strict;
use warnings;
my $dir = q{dirA};
opendir my $dh, $dir or die qq{opendir: $dir: $!\n};
while ( my $file = readdir $dh )
{
if ( $file eq q{fileB} )
{
print qq{unlinking $dir/$file ... };
unlink qq{$dir/$file} or die qq{unlink: $dir/$file: $!\n};
print qq{done\n};
last;
}
else
{
print qq{$dir/$file\n};
}
}
print qq{+++++++++++\n};
rewinddir $dh;
while ( my $file = readdir $dh )
{
print qq{$dir/$file\n};
}
Here's the output.
dirA/.
dirA/..
dirA/fileA
unlinking dirA/fileB ... done
+++++++++++
dirA/.
dirA/..
dirA/fileA
dirA/fileC
dirA/fileD
dirA/fileE
I hope this is of use. Cheers, JohnGG |