Of the solutions already posted, none of them seem to address the fact that you also wanted to print an error message when removing one of the elements from the list. Here's an elegant way to do that:

my @dirs = qw#/usr /tmp Kitten.gif /sys /var/run /nonexistent /root#; @dirs = map { warn "`$_' is not a directory\n" if not -d; -d _ ? $_ : () } @dirs; print "\nThe following are valid: @dirs\n";

Output:

`Kitten.gif' is not a directory `/nonexistent' is not a directory The following are valid: /usr /tmp /sys /var/run /root

The major point of learning, here, is probably the fact that map uses the result of the last statement in the block: in this case, the result of the conditional operator: either the directory name, or an empty list, if it's not a directory.

Edit: Thanks RonW for reminding me of _. I left my original paragraph below the <readmore> for continuity's sake, but have updated the code above—and had my 1st cup of coffee.

(Previous sub-optimal advice, no longer applicable to the above code): Yes, I use the -d test twice, but my reasoning is, it's cleaner, and the (very) slight hit to efficiency is only really going to be noticeable on extremely slow and non-cached media or extremely large lists of directories (and even then I'm not sure without a benchmark). If that's of particular concern, you can always do my $is_dir = -d; and use that instead.

use strict; use warnings; omitted for brevity.

In reply to Re: Best way to remove elem of for loop by rjt
in thread Best way to remove elem of for loop by HarryPutnam

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.