nessundorma has asked for the wisdom of the Perl Monks concerning the following question:

I am troubleshooting one of my scripts, and at this point am just looping over all the files in a directory and printing the filenames to the screen. I only put one file in the directory, but my output is as follows:
.
..
file.out
How can I get rid of this?

Replies are listed 'Best First'.
Re: Too many files
by pc88mxer (Vicar) on Jun 03, 2008 at 16:27 UTC
    The entries . and .. are created by the operating system and will always exist in every directory. Normally the command that lists the files in a directory (e.g. ls on Unix systems or dir on Windows) doesn't show them, but they are there nonetheless. It's the job of your script to ignore them.

    One way is to simply test for them:

    opendir(D, "/some/directory"); my @entries = readdir(D); closedir(D); for my $f (@entries) { next if ($f eq "." or $f eq ".."); ... }
    If you can safely ignore any files that begin with a dot, consider using glob() with a star:
    my @entries = glob("/some/directory/*"); ...
    A third way is to skip all entries that are not files:
    opendir(D, "/some/dir"); my @entries = readdir(D); closedir(D); for my $f (@entries) { next unless -f "/some/dir/$f"; ... }

      The entries . and .. are created by the operating system and will always exist in every directory.

      Nit: They don't exist in the root directory on Windows.

      Yes, I figured they were the current/parent directories, but I am unsure how to skip over them. I've tried a few different lines in my code, but none of them work and I feel like I'm missing something obvious...
Re: Too many files
by apl (Monsignor) on Jun 03, 2008 at 16:32 UTC
    How can I get rid of this?
    I assume "this" are the current and parent directories. If that's the case, change

    print $path;
    to
    print $path if ( some_test_or_another );

    What do you think some_test_or_another should be?

      some_test_or_another is $path != current_directory which does seem to work, thank you. Before I had been trying to do something similar, with the if statement before the print statement instead of hooked onto the end, and for some reason could not get the script to work
        If you post your code, the Monks could give more specific advice. Otherwise, we're forced to look at the entrails of a goat, which is far less precise.
Re: Too many files
by sub_chick (Hermit) on Jun 03, 2008 at 16:38 UTC
    I don't know if your script consists of using the unix command
    ls
    but as already said, only
    ls -a gives you . and ..
    But you could compose a regex to only count alphas and numbers possibly.


    Es gibt mehr im Leben als Bücher, weißt du. Aber nicht viel mehr. - (Die Smiths)"