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.

Re: Analysing text files to obtain statistics on their content Using P

mediastormmediastorm Posts: 2Member
Can anyone get this code to run?
Re: Analysing text files to obtain statistics on their content Using Perl

#!/usr/bin/perl



use strict;

use warnings;



my $filename= "";

if ($#ARGV == -1) #no filename provided as a command line argument.

{

print("Please Enter Filename: ");

$filename = ;

chomp($filename);

}

else

{

$filename = $ARGV[0];

}

if ($filename !~ m/^[_a-zA-Z][^.]{1,7}.TXT$/i)

{

die("File is not valid.
");

}

if ($filename !~ m/.TXT$/i)

{

$filename.=".TXT";

}

if (-e $filename)

{

die("File does not exist
");

}



#check if filename is empty, exit if it is.

if (-s $filename)

{

die("File is empty
");

}

open(READFILE, $filename) or die ("Can't open file $filename");



#then use a while loop and series of if statements similar to the following

while () {

chomp; #removes the input record Separator

my $i = $.; #"$". is the input record line numbers, $i++ will also work

my $p++ if (m/^$/); #count paragraphs

my @t = split (/s+/); #split sentences into "words" and store them in @t

my $words+= @t; # add count to $words

my $chars += tr/ //c; #tr/ //c replaces everything in the string with itself, except spaces, and returns the number of such characters replaced

#count all characters except spaces and add to $chars

}





my $sentences = 0;

my $i = 0;

my $p = 1;

my $words = 0;

my $chars = 0;







while(my $ch = getc(READFILE))

{



my $character_count;



chomp($ch);

if($ch eq "?" || $ch eq "," || $ch eq ".")

{

$sentences++;

}

}



my $word++;

if(my $ch =~ /[ ]+/)

{

$chars++;

}



close(READFILE);



#display results



print("Sentences: $sentences
");

print("Lines: $i lines
");

print("Paragraphs: $p paragraphs
");

print("Words: $words
");

print("Characters: $chars
");
Sign In or Register to comment.