in reply to Read And modify a series

Per OP Update: I have an array Say, @array1 = qw (1,1,1,2,3,4,4,4,5,6,1,1,1,1,...). From this array i have to extract an output as "1,1,1,2,3,4,4,4,5,6,1" (i.e. to remove the X-number of 1's with just 1).

One way:

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @ra = (1, 1, 1, 2, 3, 4, 4, 4, 5, 6, 1, 1, 1); dd \@ra; ;; my $one; $one = pop @ra while $ra[-1] == 1; push @ra, $one if defined $one; dd \@ra; " [1, 1, 1 .. 4, 4, 4, 5, 6, 1, 1, 1] [1, 1, 1 .. 4, 4, 4, 5, 6, 1]

Update: Another way:

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @ra = (1, 1, 1, 2, 3, 4, 4, 4, 5, 6, 1, 1, 1); dd \@ra; ;; my $highest; for my $i (reverse 0 .. $#ra) { last if $ra[$i] != 1; $highest = $i; } $#ra = $highest if defined $highest; dd \@ra; " [1, 1, 1 .. 4, 4, 4, 5, 6, 1, 1, 1] [1, 1, 1 .. 4, 4, 4, 5, 6, 1]

Upon reflection, I think the second approach is better: it's more flexible. If one wanted to trim all but one undef value from the end of an array, one need only change the test within the for-loop from
    last if $ra[$i] != 1;
to
    last if defined $ra[$i];
and the job's done. The first approach does not have this flexibility.


Give a man a fish:  <%-(-(-(-<

Replies are listed 'Best First'.
Re^2: Read And modify a series
by DarshanS (Initiate) on May 26, 2015 at 12:22 UTC
    My Sincere apologies, Series can be in any order. Not necessarily ascending, can be any random number in-between the 1's. Between the value '5' & '6', as demonstrated below, there will not be any 1's either. Say: my @array1 = (1,1,1,5,3,4,4,4,2,6,1,1,1,1,1); Expected output:(1,1,1,5,3,4,4,4,2,6) or (1,1,1,5,3,4,4,4,2,6,1) : getting anyone of it is fine.

      You've been given solutions that will give you either of these outputs. Take your pick.


      Give a man a fish:  <%-(-(-(-<

        It works AM, thanks a lot. Good day.