[ale] Perl Question

Danny Cox danny at compgen.com
Mon Oct 16 15:30:33 EDT 2000


On Mon, 16 Oct 2000, Ken Nagorski wrote:

> But checking the next line wasn't the problem, if the pattern matched I
> wanted to line above it and below it. See why redo didn't help? Even
> though I solved my current problem I would still love to know how to do
> this.

	Ah!  In your original plea, you only wanted to print the matching
line, and the line after it.  'grep -2 ...' is equivalent to 'grep -A2 -B2
...'.
> >     
> >         Suguestions to use system to call grep from perl are almost as 
> > bad as using cat to pipe files to grep on the command line. :)

	Almost, but not quite ;-).

	How about:

	$prev = '';
	$print_next = 0;
	while (<>) {
		if (/pattern/) {
			print $prev, $_;
			$print_next = 1;
		}
		elsif ($print_next) {
			print;
			$print_next = 0;
		}
		$prev = $_;
	}

	?  I've not texted it, but it should be close!

	Another thought, but may require lots of memory:

	@lines = <>;

	for ($i = 0; $i < $#lines; ++$i) {
		if ($lines[$i] =~ /pattern/) {
			print $lines[$i-1];
			print $lines[$i];
			print $lines[$i+1];
		}
	}

	I don't check for $i out-of-bounds.  I don't know what you wish to
print if the first line matches, for example.

Danny

--
To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.





More information about the Ale mailing list