Perl

Moderators: Jonathan
Number of threads: 1211
Number of posts: 3568

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Re: Analysing text files to obtain statistics on their content Using P Posted by mediastorm on 6 Sept 2009 at 6:49 AM
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 = <STDIN>;

chomp($filename);

}

else

{

$filename = $ARGV[0];

}

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

{

die("File is not valid.\n");

}

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

{

$filename.=".TXT";

}

if (-e $filename)

{

die("File does not exist\n");

}



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

if (-s $filename)

{

die("File is empty\n");

}

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 (<READFILE>) {

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 =~ /[ \t]+/)

{

$chars++;

}



close(READFILE);



#display results



print("Sentences: $sentences\n");

print("Lines: $i lines\n");

print("Paragraphs: $p paragraphs\n");

print("Words: $words\n");

print("Characters: $chars\n");



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.