in reply to search array for closest lower and higher number from another array

Your method requires 2 full passes of the file, and then creates the problem of trying to relate the results of the two.

Far simpler would be to do a single pass, remembering each section and discarding it when you see the start of a new one. And then print the remembered section when you see the search term. You have a single pass, that on average will complete half way through the file, and no silly games trying to relate two separate searches.

Ie:

#! perl -sw use strict; my $term = shift; my @section; while( <DATA> ) { @section = () if /Header/; push @section, $_; if( /$term/ ) { print for @section; print while defined( $_ = <DATA> ) and not /^Header/; last; } } __DATA__ Header 1 just some junk just some junk just some junk just some junk just some junk Header 2 just some junk just some junk just some junk just some junk just some junk Header 3 just some junk just some junk just some junk this is a term just some junk just some junk Header 4 just some junk just some junk just some junk just some junk just some junk Header 5 just some junk just some junk a different term just some junk just some junk just some junk

A couple of sample runs:

c:\test>junk34 term Header 3 just some junk just some junk just some junk this is a term just some junk just some junk c:\test>junk34 different Header 5 just some junk just some junk a different term just some junk just some junk just some junk

Note that this stops looking the first time it matches the term. To display all sections containing the term, just delete the last statement.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.