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


in reply to Extracting Text Lines

That code doesn't do what you say it does. It searches through the file then prints the line after your target line, and every 3rd line after that till the end of the file. The reason is that the inner while loop continues until the file ends. Also the readline doesn't do what you mean for it to do, it actually reads a line from the file (<FILE>) then uses that as a argument to readline. If you had used warnings it would have complained about a readline on unopened filehandle. readline(FILE)is the same as <FILE> and is not restricted to a while loop so where ever you read that is wrong. Here is a way over commented piece of code that does what you say you want :)

use warnings; use strict; my $success = 0; open(FILE, "<", "dumptape.log") or die "Couldn't open dumptape.log: $!"; while (<FILE>) { if (/Dump phase number 3/) { # We found the line my $line = <FILE>; # read the next line print $line; # print the next line <FILE>; # Skip a line <FILE>; # Skip a line $line = <FILE>; # read the fourth line print $line; # print the fourth line $success = 1; # we found it last; # So we're done! } } close FILE; if (! $success) { print "Failed dump log\n"; }

Replies are listed 'Best First'.
Re: Re: Extracting Text Lines
by liz (Monsignor) on Jul 31, 2003 at 08:01 UTC
    my $line = <FILE>; # read the next line print $line;
    I think these two lines are only needed because you want to provide a scalar context to <FILE>. That can be done easier and more efficiently (and probably more readable as well):
    print scalar <FILE>; # read the next line and print it
    Liz