Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read a file two lines at a time

Status
Not open for further replies.
Apr 30, 2003
56
US
I need to write a perl script that will read a report two lines at a time.

The report like the following:

SQL>connect aaaaa/aaaaa
Connected.
SQL>connect bbbbb/bbbbb
Connected.
SQL>connect ccccc/ccccc
ERROR

If the second line shows connected then print "aaaaa, Your Password is the same as your username. You need to change you password."
"bbbbb, Your Password is the same as your username. You need to change you password."

If the second line shows error then print "ccccc, Your password has pass the security test."
I know how to use perl script to read a file line by line, but how to read two lines at same time? Does any one know? Please help. Thanks.
 
After opening the file, you could try something like that:

$row1 = <FIN>;
$row2 = <FIN>;

This will read the next two lines of the file and you could then evaluate the value of $row2. Reading two lines at a time is not possible. Alternatively you could also read the entire file into an array (@rows = <FIN>;) and then step through the array.

Hope this helps.
 
You can read two lines at once by changing the input record seperator ($/) to two newlines, but that essentially means the two lines are concacted into one line, swisschris's method is probably better. Untested code:

Code:
open(FH,'file.txt') or die "$!";
while(<FH>) {
   chomp (my($line1,$line2) = (<FH>,<FH>));
   if ($line2 eq lc('connected')) and $line1 =~ /^SQL>connect (\w+)\/(\w+)/i){
      print "$1, Your Password is the same as your username. You need to change you password.\n";
   }
   elsif ($line2 eq lc('error') and $line1 =~ /^SQL>connect (\w+)\/(\w+)/i){
      print "$1,  Your password has passed the security test.\n";
   }
   else {
      print "Error in the input.\n";
   }
}
 
Maybe I'm misunderstanding you Kevin, but won't setting $/ to "\n\n" cause it to read lines until there's a doublespace? It won't necessarily read two lines (and given the sample data, it would read many more than 2 lines.)
 
You did not misunderstand me, I was totally wrong, not sure what I was thinking (or not thinking is probably more accurate). [rednose]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top