September 2008
Intermediate to advanced
280 pages
6h 31m
English
We will use the following example, textcount.pl, which computes statistics on text files:
1 #! /usr/bin/perl
2
3 # reads the text file given on the command line, and counts words,
4 # lines, and paragraphs
5
6 open(INFILE,@ARGV[0]);
7
8 $line_count = 0;
9 $word_count = 0;
10 $par_count = 0;
11
12 $now_in_par = 0; # not inside a paragraph right now
13
14 while ($line = <INFILE>) {
15 $line_count++;
16 if ($line ne "\n") {
17 if ($now_in_par == 0) {
18 $par_count++;
19 $now_in_par = 1;
20 }
21 @words_on_this_line = split(" ",$line);
22 $word_count += scalar(@words_on_this_line);
23 }
24 else {
25 $now_in_par = 0;
26 }
27 }
28
29 print "$word_count $line_count $par_count\n";
The program counts the number of words, lines, and paragraphs ...
Read now
Unlock full access