in reply to Ignore a range of numbers ina List

Strange, I had expected people to suggest something more like this, albeit simplistic and non-terse:-
use Data::Dumper; my $aref = [1, 6, 2, 2, 7, 1, 6, 99, 99, 7]; my @new = (); my $flag = 0; for (@$aref) { $flag = 1 if (!$flag and $_==6); push @new, $_ if !$flag; $flag = 0 if ($flag and $_==7); } $aref = \@new; print Dumper $aref;

One world, one people

Replies are listed 'Best First'.
Re^2: Ignore a range of numbers ina List
by Laurent_R (Canon) on Jun 25, 2017 at 09:33 UTC
    This won't work if the list has a six not followed somewhere by a seven, for example with a list like:
    my $aref = [1, 6, 2, 2, 7, 1, 6, 99, 99, 7, 5, 3, 6, 5, 88];
    the last three digits are omitted from the result, although they are not in a 6..7 range.
      Sure, but I was explaining algorithm for the OP and was deliberately avoiding that part of the discussion, because normally, one does not allow e.g. a left bracket without a right bracket before even letting the data through to the processing phase - that is a "syntax error" in my book. So in my example, if the flag is still turned on after the loop I would terminate with an error message, unless the OP specifically stated that an unterminated 6 is allowed, in which case I would save what isn't being pushed into a separate array and push it at the end if the flag is still turned on i.e.:
      use Data::Dumper; my $allow_loose6 = 1; my $aref = [1, 6, 2, 2, 7, 1, 6, 99, 99, 7]; my @new = (); my @loose = (); my $flag = 0; for (@$aref) { $flag = 1 if (!$flag and $_==6); if (!$flag) { push @new, $_; } else { push @loose, $_; } if ($flag and $_==7) { $flag = 0; @loose = (); } } $aref = \@new; if ($allow_loose6) { push @$aref, @loose; } elsif (@loose) { die "Unterminated 6 detected"; } print Dumper $aref

      One world, one people

        Yes, you're right, the OP did not specify this possibility, so this may or may not be needed. But taking this possibility into account was what made the solutions suggested by other monks slightly more complicated.

        Note that you probably don't need to test $flag in the statements where you change its value. For example the loop of your first solution could be simplified as follows:

        for (@$aref) { $flag = 1 if $_== 6; push @new, $_ unless $flag; $flag = 0 if $_== 7; }