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 dir
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.
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);
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;
}
To test string you have to use eq
:
if($file eq "." || $file eq ".."){ next;}
or:
next if $file =~ /^\.\.?$/;
this works and skips the first 2 . and ..
if($fil !~ m/^\.+/i)
{
your stuff here
}