This uses push and unshift as others have advocated. The searching has been moved into a more generic subroutine that takes array references for the array to search and indices array to update, a code reference for the selection criterion, and scalars for how many to look for, starting index and whether to search in reverse.
use strict; use warnings; use List::Util qw{ first }; my @dataLines = map { [ $_, split m{,|\s} ] } <DATA>; my @indices = (); push @indices, first { $dataLines[ $_ ]->[ 2 ] eq q{Red} } 0 .. $#dataLines; findNext( \ @dataLines, \ @indices, sub{ $_[ 0 ]->[ 2 ] eq q{White} }, 4, $indices[ -1 ] + 1, 0 ); findNext( \ @dataLines, \ @indices, sub{ $_[ 0 ]->[ 2 ] eq q{White} }, 4, $indices[ 0 ] - 1, 1 ); findNext( \ @dataLines, \ @indices, sub{ $_[ 0 ]->[ 2 ] eq q{Blue} }, 1, $indices[ -1 ] + 1, 0 ); findNext( \ @dataLines, \ @indices, sub{ $_[ 0 ]->[ 2 ] eq q{Blue} }, 1, $indices[ 0 ] - 1, 1 ); print $dataLines[ $_ ]->[ 0 ] for @indices; sub findNext { my( $raLookIn, $raRecord, $rcSelect, $howMany, $startIdx, $reverse ) = @_; return if $reverse ? $startIdx < 0 : $startIdx > $#{ $raLookIn }; for my $idx ( $reverse ? reverse 0 .. $startIdx : $startIdx .. $#{ $raLookIn } ) { next unless $rcSelect->( $raLookIn->[ $idx ] ); if( $reverse ) { unshift @$raRecord, $idx; } else { push @$raRecord, $idx; } return unless -- $howMany; } } __END__ 1.00,Blue,12:00 40.20,White,12:00 80.30,White,12:00 120.00,White,12:00 126.00,White,12:00 162.43,White,12:00 198.86,White,12:00 235.29,White,12:00 271.72,Red,03:45 308.15,White,12:00 344.58,White,12:00 381.01,White,12:00 417.44,White,12:00 453.87,White,12:00 490.30,White,12:00 526.73,White,12:00 563.16,Red,07:45 599.59,White,12:00 636.02,White,12:00 672.45,White,12:00 708.88,White,12:00 745.31,White,12:00 781.74,White,12:00 818.17,White,12:00 854.60,Blue,12:00 891.03,White,12:00 963.89,White,12:00 1000.32,White,12:00 1036.75,Red,08:30 1073.18,White,12:00 1109.61,Red,06:00 1146.04,White,12:00 1182.47,White,12:00 1218.90,White,12:00 18516.40,Blue,12:00 1255.33,White,12:00 927.46,White,12:00
The output
1.00,Blue,12:00 126.00,White,12:00 162.43,White,12:00 198.86,White,12:00 235.29,White,12:00 271.72,Red,03:45 308.15,White,12:00 344.58,White,12:00 381.01,White,12:00 417.44,White,12:00 854.60,Blue,12:00
I hope this is of interest.
Cheers,
JohnGG
In reply to Re: Extracting array elements on either side of a match
by johngg
in thread Extracting array elements on either side of a match
by punkish
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |