Download code

Jump to: navigation, search

Back to Word_count_(Perl)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

wc.perl

 1 # The authors of this work have released all rights to it and placed it
 2 # in the public domain under the Creative Commons CC0 1.0 waiver
 3 # (http://creativecommons.org/publicdomain/zero/1.0/).
 4 # 
 5 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 # 
13 # Retrieved from: http://en.literateprograms.org/Word_count_(Perl)?oldid=18681
14 
15 
16 #!/usr/bin/env perl
17 
18 
19 use strict;
20 use warnings;
21 
22 sub printwc
23 {
24 	my ($fname, $opts, $lines, $words, $chars)=@_;
25 
26 	$opts=~/l/ && printf("% 8d", $lines);
27 	$opts=~/w/ && printf("% 8d", $words);
28 	$opts=~/c/ && printf("% 8d", $chars);
29 	$fname ne "-" && print " $fname";
30 	print "\n";
31 }
32 sub wc
33 {
34 	my ($fname)=@_;
35 	my $lines=0;
36 	my $words=0;
37 	my $chars=0;
38 
39 	open(FILE, $fname) || die "Couldn\'t open file $fname";
40 	foreach my $line (<FILE>) {
41 		$chars+=length($line);
42 		$line=~/\n$/ and ++$lines;
43 
44 		$line=~s/^[ \t]*//g;
45 		$line=~s/[ \t\r\n]*$//g;
46 		my @w=split(/[ \t]+/, $line);
47 		$words+=@w;
48 	}
49 
50 	close(FILE);
51 
52 	return ($lines, $words, $chars);
53 }
54 
55 sub usage
56 {
57 	print "Usage: $0 [-cwl] [<fname>*]\n";
58 	exit 1;
59 }
60 
61 
62 my $nfiles=0;
63 my $opts;
64 my ($tot_lines, $tot_words, $tot_chars);
65 
66 my $arg;
67 while($arg=shift(@ARGV) and $arg=~/^-/) {
68 	$arg=~/^-[lwc]+$/ or usage();
69 	$opts.=substr($arg, 1);
70 }
71 $opts or $opts="lwc";
72 
73 while($arg) {
74 	++$nfiles;
75 	my ($lines, $words, $chars)=wc($arg);
76 	$tot_lines+=$lines;
77 	$tot_words+=$words;
78 	$tot_chars+=$chars;
79 	printwc($arg, $opts, $lines, $words, $chars);
80 	$arg=shift;
81 }
82 
83 if($nfiles<1) {
84 	my ($lines, $words, $chars)=wc("-");
85 	printwc("-", $opts, $lines, $words, $chars);
86 } elsif($nfiles>1) {
87 	printwc("total", $opts, $tot_lines, $tot_words, $tot_chars);
88 }
89 
90 exit 0;
91 


hijacker
hijacker
hijacker
hijacker

build.log

1 /tmp/litprog4914239/wc.perl syntax OK