Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k & phranque

counting commas in a text file

A novice on regular expressions!

10:55 pm on Jan 18, 2009 (gmt 0)

5+ Year Member

I have a text file and I would like to count the number of commas in the file.

I have six commas in the file and when I do this code...

while ($line = <IN>)
if($line =~ m/[\,]/){$comma++;}
print ("$comma");

It says I have four. I have two period characters and when I ammend the code to recognise the periods...

if($line =~ m/[\.]/){$sen++;}

It correctlys says I have just two periods. So how would I make the file recognise the commas?

[edited by: phranque at 2:04 am (utc) on Jan. 19, 2009]
[edit reason] disabled graphic smileys ;) [/edit]

7:02 am on Jan 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Try loading your file into an array first, then join the lines together into a single string to parse for commas.

my @line = <IN>;
$line = join("\n",@line);
$comma++ while $line =~ /\,/g;

Your code is probably parsing the first line of the text file up to the newline and ignoring the other lines.

7:10 am on Jan 19, 2009 (gmt 0)

5+ Year Member

Ignoring other problems with your code, the correct way to count a character using the method you are using is like so:

$comma = 0;
while ($line = <IN>) {
$comma++ while ($line =~ /,/g);
print $comma;

the better way is like this:

$comma = 0;
while ($line = <IN>) {
$comma += $line =~ tr/,/,/;
print $comma;

You should try and use regular expressions for matching patterns. Counting a character is not a pattern, so using the tr/// operator is way more efficient.

[edited by: phranque at 9:23 am (utc) on Jan. 19, 2009]
[edit reason] disabled graphic smileys ;) [/edit]

4:04 am on Jan 24, 2009 (gmt 0)

5+ Year Member

Thanks guys. I happy with krugs first example as I still getting to grips with arrays and I have yet to learn the translation operator
8:25 pm on Jan 24, 2009 (gmt 0)

5+ Year Member

You can learn the tr/// operator in five minutes. It has very few options and is no where near as powerful and complicated as m// or s/// regular expressions. The perl FAQS has many cookbook style answer/question FAQS that all perl coders should become familiar with.
They come with perl or you can read them online:



Featured Threads

Hot Threads This Week

Hot Threads This Month