[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Word Count Programme..



Hi,

You know, reading your code carefully for typos, missing $'s, and so on, is
always a good thing to do before asking for help. :-)

Also, well-formatted code is so much more enjoyable to read and review...

And if you're going to write things like $WordCount = $WordCount + 1, you
might as well be programming in Pascal. Try to "think Perl", it is a cool
language with loads of power.

I thought you might enjoy to see how simple things can be in perlish
(tested for accuracy against the results BBEdit gives).

-------------------
#!/usr/bin/perl -lw

use strict;

my $filename = 'sample.txt';
my ($charcount, $wordcount, $linecount) = (0,0,0);

open(F, $filename)
   or die "Error opening $filename: $!";

use locale;
while (<F>) {
   $charcount += () = /./gs; # newline counts as a character
   $wordcount += () = /\w+/g;
   $linecount++;
}
no locale;

close F;

print "Characters:  $charcount";
print "     Words:  $wordcount";
print "     Lines:  $linecount";
__END__

Good luck,
AndrŽ

==========================

>Hi!
>
>I have a small programme for counting words.  I am unable to
>find where I have gone wrong.  Can anyone please help me find
>the fault?
>
>#!/usr/bin/perl -w
>
>$TheFile="sample.txt";
>open (INFILE,$TheFile) or die "The file $TheFile could not be found.\n";
>
>$CharCount=0;
>$WordCount=0;
>$LineCount=0;
>
>while (<INFILE>) {
>$TheLine = $_;
>chomp($TheLine);
>$LineCount = $LineCount + 1;
>$LineLength = Length($TheLine);
>$CharCount = $CharCount + $LineLen;
>
>if ($TheLine eq "") {next};
>$WordCount = $WordCount + 1;
>$CharPos = 0;
>until ($CharPos == $LineLen) {
>if (substr($TheLine, $CharPos, 1) eq "")
>{$WordCount = $WordCount +1}
>$CharPos = $CharPos + 1;
>}
>}
># All finished, now print the results
>print "For the file $TheFile:\n";
>print "Number of characters  $CharCount:\n";
>print "Number of words  $WordCount:\n";
>print "Number of Lines  $LineCount:\n";
>
>When I ran the syntax check it showed the following.
>
># Name "main::LineLength" used only once: possible typo.
>File 'Hard Disk:Desktop Folder:wordcount program'; Line 14
># Hard Disk:Desktop Folder:wordcount program syntax OK

--
AndrŽ Leclerc
alecler@cam.org



***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch