http://www.perlmonks.org?node_id=1075197


in reply to How do I completely remove an element from an array?

I'm no perl monk but I'll offer this as another way to do it:
#!/usr/bin/perl use strict; # the original array elements my @a = ('1', '2', '3', '4', '5', '6', '7'); # the element we want to remove my $removeThis=3; # container for array elements my $arrayElement; # Temporarily Store the elements we want to keep here my @b; foreach $arrayElement (@a) { # it the element does not match the one we # want to remove we add it to the @b array: if ($arrayElement ne $removeThis) { push(@b, $arrayElement) } } # replace the elements in the @a array with those in # the @b array: @a=@b; # now print it out foreach $arrayElement(@a) {print $arrayElement} #result: #124567
And I suppose if you want to turn it into a one liner this qualifies:
for $i(@a){if($i ne $m){push(@b,$i)}} @a=@b;
I honestly wouldn't know if there are any disadvantages to this approach. Perhaps others will comment on that.

Replies are listed 'Best First'.
Re: Answer: How do I completely remove an element from an array?
by choroba (Cardinal) on Feb 17, 2014 at 18:20 UTC
    I would probably not declare $arrayElement in the broad scope, but instead use a lexical loop variable in each loop:
    for my $arrayElement (@a) { ... }

    The broad scope has no advantage, as the variable is localized anyway:

    If the variable is preceded with the keyword "my", then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with "my", it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a "foreach" loop.

    (From perlsyn)

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ