We were using Win32::Internet or perhaps Net::FTP and getting back a listing of files and we wanted to filter out the '.' and '..' from a directory listing. I had just finished reading Simon Cozen's article on grep at perlarchive.com, so voila:
@filtered_directory = grep !/^[.]{1,2}$/, @directory;

Replies are listed 'Best First'.
RE: Remove '.' and '..' from a list of filenames
by merlyn (Sage) on Aug 22, 2000 at 23:11 UTC
    Just watch out, from a security perspective you are also filtering ".\n" and "..\n", which might then sneak by in a file listing when they shouldn't.

    -- Randal L. Schwartz, Perl hacker

      I didn't vote you down, but I can see perhaps why someone did. Isn't your reply incorrect? For example, if I write the following:
      @vals = (".","..",".\n","..\n","foo","foo\n","bar","bar\n"); foreach (grep !/^[.]{1,2}$/,@vals) { print "$_\n"; }
      It spits out:
      foo foo bar bar
      ...as I would expect. It filtered out ".\n" and "..\n" just fine. Can you elaborate?
        ..\n is a valid, albeit very bizarre, file name. This regex would incorrectly filter them out. I believe a more correct solution is to say /\.\.?\z/ \z is a zero width assertion that is true when you are at the actual end of the line as opposed to $, which anchors to the end of the line or possibly \n and the end of the line.

        mikfire

        A reply falls below the community's threshold of quality. You may see it by logging in.
        Ahh, the problem is that it filters those out when it shouldn't. Sorry, reversed logic strikes. In other words,
        /^\.$/
        matches both dot and dot-newline, and if you were expecting it to match only dot, you could be in for a big shock.

        I've edited the original note to reflect what I meant, not what I said. {grin}

        -- Randal L. Schwartz, Perl hacker

RE: Remove '.' and '..' from a list of filenames
by kilinrax (Deacon) on Sep 04, 2000 at 23:36 UTC
    What's wrong with this? :
    @filtered_directory = grep { $_ ne '.' && $_ ne '..' } @directory
    I know TMTOWTDI, but I would have thought that not using a regular expression was probably more efficient ;-)