sub findtext { my ($files, $terms) = @_; my @filenames; for my $arg ( @$files ) { push @filenames, grep /\w/, split( /\W+/, $arg ); } my %target; $target{$_} = undef for @$terms; local $/ = undef; # this only applies within the sub for my $file ( @filenames ) { unless ( open( FILE, "/home/jroberts/$file.txt" )) { warn "open failed on $file: $!"; next; } $_ = ; # read full text; close FILE; my @words = split; # @words has all words in $file for ( @words ) { s{(.*)}{$1} if ( exists( $target{$_} )); } # all target words in $file are now marked, so # print the sequences that contain marked words my $printing = 0; for my $i ( 0 .. $#words ) { if ( $words[$i] =~ // ) { if ( $i and $printing == 0 ) { # backtrack for prior context my $j = ( $i >= 6 ) ? $i - 6 : 0; print join " ", @words[$j..$i-1]; } print $word[$i]; # (update: have to print this every time) $printing = 6; # number of following words to print } elsif ( $printing ) { print $words[$i]; $printing--; print "\n
\n" if ( $printing == 0 ); } } } }