问题
Following up from here: Perl Imgsize not working in loop? I have another question - how do I not let perl list the single and double dot entries when it reads the files in a directory?
As in the linked question above, my output to the while loop (while ($file = readdir($dh))) is something like this:
.
..
file1.jpg
file2.jpg
file3.jpg
file4.jpg
file5.jpg
And this creates problems because I've also got a counter somewhere, which is counting my files. And . and .. don't count as files, so my counter is giving a greater number of files in my directories than there really are.
I added if($file == "." || $file == ".."){ continue;} and if ($file ~ /^\./ or $file ~ /^\.\./) {continue;} and different variations of that to the beginning of the while loop... but I keep getting an abort "due to compilation errors".
How can we get a hold of the single and double dot entries?
回答1:
To test string you have to use eq:
if($file eq "." || $file eq ".."){ next;}
or:
next if $file =~ /^\.\.?$/;
回答2:
I'm going to suggest something else - don't use readdir and instead use glob.
my @dirlist = glob ( "$dir/*.jpg" );
And then you'll get a list of paths to files matching that spec. This is particularly useful if you're doing:
foreach my $file ( glob ( "/path/to/file/*.jpg" ) ) {
open ( my $input, '<', $file ) or die $!;
}
Where with readdir you'll only get a filename, and have to reconstruct the path yourself.
回答3:
this works and skips the first 2 . and ..
if($fil !~ m/^\.+/i)
{
your stuff here
}
回答4:
I have come to another solution, which works for me to delete all files in a subfolder temp - not starting with first file (0) but only with third file (2):
#!/bin/perl
@AllFiles = ();
opendir(DIRECTORY, "temp");
@AllFiles = readdir(DIRECTORY);
closedir DIRECTORY;
print $#AllFiles-1 ."\n"; #Show 3 for three files, as it shows number of last file: 0=. 1=.. 2=aaa.txt 3=bbb.xml 4=ccc.pdf
$FileNumber = 2; #Starting with file 2, don't need to try deleting current and parent folders
until($FileNumber > $#AllFiles ) {
unlink ("temp/" . $AllFiles[$FileNumber]);
print $FileNumber-1 . ": temp/" . $AllFiles[$FileNumber] . "\n"; #show file numbers as 1=aaa.txt 2=bbb.xml 3=ccc.pdf
$FileNumber += 1;
}
回答5:
If you're getting the directory contents in list context, you can use grep to filter out the dotfiles:
opendir (my $dh, $src) || die "Can't opendir $src: $!\n";
my @entries = grep {!/^\./} readdir($dh);
closedir ($dh);
来源:https://stackoverflow.com/questions/21203350/how-to-ignore-the-single-and-double-dot-entries-in-perls-readdir