Perl : How is file handling working here??

Hi,

I have a perl script which is just reading from the file but what I would like to understand is how the counter is moving without using the loop in the script.

Below are the details:

$ more /tmp/abc.txt
This is 0
This is 1
This is 2
This is 3
This is 4
This is 5
This is 6
This is 7
This is 8
This is 9

Script to read the above file is as :

$ more file1.pl
#!/usr/bin/perl
#
sub readfile
{
     my ($rec,$INFO);
     $INF=shift;
     if (defined($rec = scalar <$INF>))
     {
          print $rec;
     }
}
$file='/tmp/abc.txt';
open(xyz,$file);
$i=0;
$tes=readfile(xyz);
$tes=readfile(xyz);

when I am executing the above script, it is throwing the output as :

$ perl file1.pl
This is 0
This is 1

How counter in the file is moving to next row when I am not moving it and I am also not using any loops anywhere? I would just like to understand that? Does that mean loops are not required for moving through the file or I am getting it wrong somewhere?

Thanks in advance for any help on this!

Everytime you do read from a filehandle and store it in a scalar variable, then one line of input is read. (By one line, I mean the data until the next record separator).

Here is how it works internally:
When you open a filehandle, lets say, there's a mark that is at the beginning of file. The first time $rec = scalar <$INF> is encountered, the first line from file is read and referred by $rec. Now, the mark that we spoke of earlier, is at the character just after newline character (assuming newline as the default record separator). Now again when $rec = scalar <$INF> is encountered, one more line of data is read.

In the example code you provided in your post, a wrapper routine "readfile" reads one line of data and prints it.

The usual way of reading a file is to use a loop. Then again, that depends on what you really want to do:

open FH, "< /path/to/file";
while ($rec = <FH>) {
    print $rec;
}
close FH;

Thanks lot for such a nice explanation Bala.

Appreciated!