Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] removing elements of an arrays on the fly

Expand Messages
  • merlyn@stonehenge.com
    ... Jeff That s a dangerous practice. You ll end up messing things up, because Jeff when you have an array like (a,b,c,d), if you re looking at element b
    Message 1 of 4 , Oct 2, 2003
      >>>>> "Jeff" == Jeff 'japhy' Pinyan <japhy@...> writes:

      Jeff> On Oct 2, Lange Gunter, CH said:
      >> is there a way to remove elements from an array as I'm iterating through an
      >> array with foreach?

      Jeff> That's a dangerous practice. You'll end up messing things up, because
      Jeff> when you have an array like (a,b,c,d), if you're looking at element 'b'
      Jeff> and you say "delete me", then the array is (a,c,d). But the next element
      Jeff> you get to will be 'd', because Perl internally just goes to the next
      Jeff> index in the array, and 'd' is the new $array[2].

      Jeff> Use a C-style for loop:

      Jeff> for ($i = 0; $i < @arr; $i++) {
      Jeff> if (CONDITION) {
      Jeff> splice @arr, $i, 1;
      Jeff> $i--; # to counteract the $i++ in the for statement
      Jeff> }
      Jeff> }

      Jeff! It's easier just to count down:

      for (my $i = $#arr; $i >= 0; $i--) {
      if (CONDITION on $arr[$i]) {
      splice @arr, $i, 1;

      Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
      <merlyn@...> <URL:http://www.stonehenge.com/merlyn/>
      Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
      See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
    Your message has been successfully submitted and would be delivered to recipients shortly.