http://www.perlmonks.org?node_id=779717

bichonfrise74 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I'm trying to do a simple equivalent of
grep -A1 -B1 'hello' file_name
in Perl. This basically prints the previous and the next line when the word 'hello' is found. I've done a super search and came up with the following links:

Grep - print matched line and next N lines
Emulating GNU grep -A and -B switches with perl

Both were created back in 2003 and I was wondering if there is now a more concise solution to this. I mean using the Linux 'grep' command, it is able to do it in one line which strikes me odd that it cannot be done in Perl in a concise manner.

Below is my code but again, I think it is too clunky and too long when compared to the Linux 'grep' command.
#!/usr/bin/perl use strict; my ($prev, $next); while (my $line = <DATA>) { if ( $next ) { print "$line"; $next = undef; } if ( $line =~ /hello/ ) { print "$prev" if defined( $prev ); print "$line"; $next++; } $prev = $line; } __DATA__ test1 test2 hello test3 test4
Thanks in advance.