Is there a built-in Perl variable that keeps track of how many records have been read in a while loop?
For example, suppose I do this:
my $count;
while (<>) {
$count++;
}
print $count;
Is there a way to do this without defining $count? That is, is there already some variable that contains this information?
$.will tell you the current line number for the current file being read.Note that the variable resets on a close() call to the filehandle, so if the old file handle isn’t closed when you start reading from a new one then the variable will keep incrementing even across files. However, if the filehandle is closed you’ll have it reset to 0. For example, the code in your example and this code will continuously count across files being read:
But if you close the filehandle at any point before the next open call:
then it’ll reset
$.to zero again and you’ll get unique counts per file.