in reply to Best way to remove elem of for loop

What you're doing is inserting '' into your array. You probably don't want to do this.

I would generally suggest you don't want to try and modify your array, and instead consider just creating a new one, with the filtered elements.

In 'foreach' terms, because 'map' makes my brain hurt:

my @filtered; foreach my $element ( @arg ) { if ( -d $element ) { push ( @filtered, $element ); }; }

If you really want to do an inplace modification, then you may want to look at setting your element 'undef'.

With map, this would probably be something like (for the sake of my own curiosity):

my @filtered = map { -d $_ ? $_ : () } @ar;

.... I think. Anyway, I prefer the former which I consider way more readable.

Replies are listed 'Best First'.
Re^2: Best way to remove elem of for loop
by Jenda (Abbot) on Apr 24, 2014 at 17:47 UTC

    You do not want map(), you want grep().

    my @filtered = grep { -d $_ } @ar; # or my @filtered = grep -d $_, @ar;

    map() means "process the elements one after another and give me the results", while grep() means "give me only those elements of the list that match the condition".

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.

      Or even:

      my @filtered = grep -d, @ar;
      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      Yes, spot on. I still think of grep in Unix terms, e.g. pattern matching. I had blanked out the bit where it can take an EXPR to evaluate. Even if I did know that underneath the hood grep and map aren't much different.

Re^2: Best way to remove elem of for loop
by HarryPutnam (Novice) on Apr 25, 2014 at 21:14 UTC
    Oh, nice

    Something similar to your code (but more primitive) was what I had been doing. I noticed the same result by doing the nul push (as you mentioned) and I thought.. ". well... its shorter ..." but I see your point. And the case posted where it had the result I wanted is way too isolated a case to use that technique at all.

    So its time well spent ... filtering/creating creating new @ar... thanks