Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

counting instances of words, lines etc in perl script

inkedinked Posts: 2Member
Hi, this code is driving me crazy, i will send the whole code to make it easier to understand. This code asks for input from the user, performs checks on the given file then proceeds to counting the number of lines, words characters paragraphs and sentences, then displaying the results. This code works fine:

[code]
#!Cperlinperl.exe



if($#ARGV == -1)
{
print("Please enter a filename ");
$file = ;
chomp($file);
}
else
{
$file = $ARGV[0];
}

if($file !~ m/^[a-zA-Z_]{1}[a-zA-Z0-9_]{7}(.txt|.TXT)$/)
{
die("Incorrect format!
");
}

if(!-e $file)
{
die("error! file does not exist!
");
}

if(-z $file)
{
die("File is empty!
");
}

open(FILE, "<$file") || die "Cant open $file: $!";

[code]

##however this code is not working and i cant figure out why:
[code]
$chars = 0;
$words - 0;
$lines = 1;
$Sentences = 0:
$paragraphs = 1;
$lastchar = ";

while($ch = getc(FILE))
{
$chars++;

if(($ch eq " " || $ch eq " " || $ch eq "
")) &&
if($lastchar ne " " && $lastchar ne " " && $lastchar ne "
"))
{
$words++;
}

chomp($ch);

if($ch eq ".")
{
$sentences++;
}

if($ch eq "
")
{
$lines++;

if($lastchar eq "
")
{
$paragraphs++;
}
}
$lastchar = $char;
}
if($lastchar ne " " && $lastchar ne "
" && $lastchar ne " ")
{
$words++;
}

close(OUT);

print("Statistics for $file
");
print("Characters: $char
");
print("Words: $words
");
print("Lines: $lines
");
print("Sentences: $sentences
");
print("Paragraphs: $paragraphs
");
[code]

##Please, please help im so frustrated with this code!!!



Comments

Sign In or Register to comment.