8.2. Counting Lines (or Paragraphs or Records) in a FileProblemYou need to compute the number of lines in a file. SolutionMany systems have a wc program to count lines in a file: $count = `wc -l < $file`; die "wc failed: $?" if $?; chomp($count); You could also open the file and read line-by-line until the end, counting lines as you go: open(FILE, "< $file") or die "can't open $file: $!"; $count++ while <FILE>; # $count now holds the number of lines read
Here's the fastest solution, assuming your line terminator really
is
$count += tr/\n/\n/ while sysread(FILE, $_, 2 ** 16); Discussion
Although you can use If you can't or don't want to call another program to do your dirty work, you can emulate wc by opening up and reading the file yourself: open(FILE, "< $file") or die "can't open $file: $!"; $count++ while <FILE>; # $count now holds the number of lines read Another way of writing this is: open(FILE, "< $file") or die "can't open $file: $!"; for ($count=0; <FILE>; $count++) { }
If you're not reading from any other files, you don't need the 1 while <FILE>; $count = $.; This reads all the records in the file and discards them.
To count paragraphs, set the global input record separator variable $/ = ''; # enable paragraph mode for all reads open(FILE, $file) or die "can't open $file: $!"; 1 while <FILE>; $para_count = $.; See Also
Your system's
wc
(1) manpage; the |
|