Greeting I have a program take in a file and lets you add stuff to it after I add some words to it i want to count all the words in the file... I am having trouble with that ...here is my code so far. I looked up stuff online but it doesnt seem to work.

#!usr/bin/perl


print "Opening file attempt\n";
open (FILE, "+<@ARGV") or die ("Unable to open file exiting\n");
print "Printing current data in file:\n";
print while (<FILE>);
print "\nType something to add to file, press Enter when done\n";
$moredata=<STDIN>;
print (FILE $moredata);
close(FILE) or die ("Can't close this?!!?!?\n");


print "Opening file attempt\n";
open (NFILE, "@ARGV") or die ("Unable to open file exiting\n");
@array = <NFILE>;
close(NFILE) or die ("Can't close this?!!?!?\n");

foreach $string (@array){
$blah=shift($string);
$blah=split(/\W+/);
$count+=blah;
print $count;
}

Any help would be very appreciated...

Recommended Answers

All 6 Replies

Is this school/class/course work? Be more specific about what you are having trouble with instead of just posting your code and saying "its not working" or "I am having trouble".

This whole block of code is just totally wrong for various reasons:

foreach $string (@array){
$blah=shift($string);
$blah=split(/\W+/);
$count+=blah;
print $count;
}

Add this line to the top of your script:

use warnings;

actually its not for anything....im doing it to learn and doing excercises out of a book from the library and it doesnt have the answers... and its been bugging me on why i cant get it

try this, assumes @array is populated correctly:

foreach $string (@array){
   @blah = split(/\W+/,$string);
   $count += @blah;
   print $count;
}

What is the title of the book?

ahh thanks! I got it to work now..... i had to manipulate my code a little bit but it works...

Whats the title of the book you are using from the Library?

One thing you have to be careful of is defining what you mean by 'word'. If your data contains only English 'words', what will your regex do with things like O'Reily, 49ers, street-wise, F.B.I. and so on. One of my most-used books is the 'Perl Cookbook' by Tom Christiansen & Nathan Torkington. This situation is covered in there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.