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: <%-(-(-(-<
In reply to Re: Read And modify a series
by AnomalousMonk
in thread Read And modify a series
by DarshanS
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |