All pastes #918853 Raw Edit

wordcount.pl

public text v1 · immutable
#918853 ·published 2008-02-26 12:16 UTC
rendered paste body
#!/usr/bin/perl

sub printwc
{
        my ($fname, $opts, $lines, $words, $chars)=@_;

        $opts=~/l/ && printf("% 8d", $lines);
        $opts=~/w/ && printf("% 8d", $words);
        $opts=~/c/ && printf("% 8d", $chars);
        $fname ne "-" && print " $fname";
        print "\n";
}

sub wc
{
        my ($fname)=@_;
        my $lines=0;
        my $words=0;
        my $chars=0;

        open(FILE, $fname) || die "Couldn\'t open file $fname";
        foreach my $line (<FILE>) {

                $chars+=length($line);
                $line=~/\n$/ and ++$lines;


                $line=~s/^[ \t]*//g;
                $line=~s/[ \t\r\n]*$//g;
                my @w=split(/[ \t]+/, $line);
                $words+=@w;
        }

        close(FILE);

        return ($lines, $words, $chars);
}


sub usage
{
        print "Usage: $0 [-cwl] [<fname>*]\n";
        exit 1;
}



my $nfiles=0;
my $opts;
my ($tot_lines, $tot_words, $tot_chars);

my $arg;
while($arg=shift(@ARGV) and $arg=~/^-/) {
        $arg=~/^-[lwc]+$/ or usage();
        $opts.=substr($arg, 1);
}

$opts or $opts="lwc";


while($arg) {
        ++$nfiles;
        my ($lines, $words, $chars)=wc($arg);
        $tot_lines+=$lines;
        $tot_words+=$words;
        $tot_chars+=$chars;
        printwc($arg, $opts, $lines, $words, $chars);
        $arg=shift;
}


if($nfiles<1) {
        my ($lines, $words, $chars)=wc("-");
        printwc("-", $opts, $lines, $words, $chars);
} elsif($nfiles>1) {
        printwc("total", $opts, $tot_lines, $tot_words, $tot_chars);
}

exit 0;