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

I am trying to search in an array "@folders",one of the element of the array is a dot".",I want to run a loop on the array elements in @folders except "."How can I do that?

foreach $mk (@folders) #except "." { }

Replies are listed 'Best First'.
Re: How to add an exceptio for"for loop"
by ikegami (Patriarch) on Mar 21, 2011 at 05:12 UTC
    foreach $mk (@folders) { next if $mk eq '.'; ... }
    or
    foreach $mk (grep !/^\.\z/, @folders) { ... }
    or
    foreach $mk (grep { $_ ne '.' } @folders) { ... }
Re: How to add an exceptio for"for loop"
by NetWallah (Canon) on Mar 21, 2011 at 04:30 UTC
    perl -e 'my @a=qw|f1 fw . f3 f4|; for (grep {$_ ne "."} @a) {print qq| +$_\n|}'

         Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

      grep will not work because other array elements also have a "." in them.I dont want a loop on the array element which is exactly "."

        I think you may be confusing the command line grep with Perl's grep command. my @selected = grep { $_ ne "." } @some_array selects elements based on whether the content of {....} returns true or false. As { $_ ne "."} is only true on an exact non-match with ".", it will exclude only ".".

        ".foobar", "foo.bar", etc. will pass the test, i.e. { $_ ne "."} will be true, and therefore will be in @selected.

Re: How to add an exceptio for"for loop"
by wind (Priest) on Mar 21, 2011 at 05:14 UTC
    for $mk (grep {!/^\.+$/} @folders) {
    Or
    for $mk @folders) { next if $mk =~ /^\.+$/;

    Either way works. Or you can just for direct equality using eq like NetWallah suggested.

    - Miller
Re: How to add an exceptio for"for loop"
by toolic (Bishop) on Mar 21, 2011 at 12:36 UTC
    If you populated your @folders array with a listing of a directory, you could use the read_dir function from File::Slurp instead because it automatically excludes the special dot directories (. and ..) for you. There is no need for you to explicitly get rid of the dot directory.
    use warnings; use strict; use File::Slurp qw(read_dir); my @folders = read_dir($dir); foreach (@folders) { # do something }