How to ignore the single and double dot entries in Perl's readdir?

后端 未结 5 891
甜味超标
甜味超标 2021-01-21 05:04

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

相关标签:
5条回答
  • 2021-01-21 05:26

    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.

    0 讨论(0)
  • 2021-01-21 05:36

    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);
    
    0 讨论(0)
  • 2021-01-21 05:43

    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;
    }
    
    0 讨论(0)
  • 2021-01-21 05:46

    To test string you have to use eq:

    if($file eq "." || $file eq ".."){ next;}
    

    or:

    next if $file =~ /^\.\.?$/;
    
    0 讨论(0)
  • 2021-01-21 05:46

    this works and skips the first 2 . and ..

    if($fil !~ m/^\.+/i)
      {
           your stuff here
      }
    
    0 讨论(0)
提交回复
热议问题