Hi All,
I am trying a simple program in PERL, but unable to get it working

$log="test.log";
open(LOGFILE, $log) or die("Could not open log file.");
foreach $line (<LOGFILE>) {
    chomp($line); 
	if($line eq "Raghu") {
		print "Found a group\n";
		$var=<LOGFILE>;
		chomp($var);
		print "$var\n";
	}
}

Whenever the line contains the letters "Raghu", I am trying to read the next line into the var variable. But nothing is getting printed as output except the statement "Found a group".
What is wrong in the code?
Thanks a lot for the time.
The test.log is as follows

Raghu
Hai

The problem is, the method you use to read from the file handle, slurps the file, and then iterates over each line by replacing $line with $_. If you really want to prove this, you can throw the special variable $. into your code. $. is a special variable in perl that represents the "current line number" in the file. If you run this code:

#!/usr/bin/perl

$log="test.log";
open(LOGFILE, $log) or die("Could not open log file.");
foreach $line (<LOGFILE>) {
    chomp($line); 
	if($line eq "Raghu") {
		print "Found a group\n";
		print "$.\n";
		$var = <LOGFILE> or die ("couldn't read: $!\n"); # Error Checking
		chomp($var);
		print "$var\n";
	}
}
close(LOGFILE);  # // How 'bout you close your open file handles :p

Your output from this will be:

Found a group
10
couldn't read:

Naturally, your line number (ie: the 10 here) will probably be different, depending on the number of lines in your file. It is important to note, that the program (with my minor modifications) dies after it tries to read from the file handle a second time.... this is because perl has slurped the file, so we have already seeked to EOF (end of file). The 10 here, shows that the current line number (in my case 10) is already at the end of the file. If this were not the case, then we would see the line with 10 change from 1 to 2 to 3, etc.

A better method for iterating over each line of the file, is to use a while loop. This will prevent perl from slurping the file, and give you the desired functionality.

#!/usr/bin/perl

$log="test.log";
open(LOGFILE, $log) or die("Could not open log file.");
while ($line = <LOGFILE>) {
    chomp($line); 
	if($line eq "Raghu") {
		print "Found a group\n";
		$var = <LOGFILE> or die ("couldn't read: $!\n"); # Error Checking
		chomp($var);
		print "$var\n";
	}
}
close(LOGFILE);  # // How 'bout you close your open file handles :p
Comments
Well said
This article has been dead for over six months. Start a new discussion instead.