Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
Re: Best way to remove elem of for loopby rjt (Curate) |
on Apr 24, 2014 at 16:47 UTC ( [id://1083648]=note: print w/replies, xml ) | Need Help?? |
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:
Output:
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 Section
Seekers of Perl Wisdom
|
|