http://qs321.pair.com?node_id=124982


in reply to Removing empty string elements from an Array

The above suggestion was great. Here's a more readable, and less efficient version:
my @newArray; foreach my $element ( @array ) { push $element, @newArray if $element; }
This should push everything you want into @newArray. It's a bit slower than the grep solution, and has additional overhead of using another array; but I find it easier to read.

Replies are listed 'Best First'.
Re: Re: Removing empty string elements from an Array
by chipmunk (Parson) on Feb 03, 2002 at 19:37 UTC
    Aside from the issue of readability, which is obviously subjective, this solution will drop any occurences of '0' from the array. A more explicit check is necessary, as in the earlier grep solutions:
    my @newArray; foreach my $element ( @array ) { push $element, @newArray if defined $element and $element ne ''; }
    (Personally, I also prefer grep to solve this problem.)
      Forgive a noob, but shouldn't
      push $element, @newArray
      be
      push @newArray, $element
Re: Re: Removing empty string elements from an Array
by chip (Curate) on Nov 13, 2001 at 10:16 UTC
    You call that "more readable"? Are you joking?

    When using any language, go with its strengths. Perl's clarity in brevity is a feature, not a bug.

        -- Chip Salzenberg, Free-Floating Agent of Chaos

      Jeez... Somebody hand me a fire extinguisher...

      Yes, I find it more readable. No, I'm not joking. It's about as close to plain English as you can get. It appeared to me that the questioner was not very familiar with some of the interesting nuances that separate perl from C or BASIC.

      When learning a language, it's often usefull to see a "here's what's happening" sort of example -- be it in pseudocode or ineffecient "straight" looping -- to show how a particular operation can happen.

      I'm sorry if my example offended you; I didn't intend to ruin your day.