Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Perl (http://www.programmingforums.org/forum21.html)
-   -   Counting a single character in a string (http://www.programmingforums.org/showthread.php?t=10693)

tbohon Jul 12th, 2006 10:53 AM

Counting a single character in a string
 
I have a list of a directory and need to process the files depending on the number of underscore characters in the file name. For example, the files
filename_date.txt

and

file_name_date.txt
will be processed differently by the script.

I've tried

$count = ($data =~ tr/_/_/);

but it doesn't seem to work - I continue to get a zero (0) for $count.

Is there a flaw in my logic above? Is there a better way to do this?

Thanks in advance!

Tom

dr.p Jul 13th, 2006 6:16 AM

You might post the other code that deals with the $count var. The example you posted looks correct.

Infinite Recursion Jul 13th, 2006 9:46 AM

This works for me:

:

#!/usr/bin/perl

my $data = "this_is_a_test.txt";

$count = ($data =~ tr/_/_/);

print("Count is: $count\n");


[ir@grendel]# ./cchar.pl
Count is: 3



As an alternative, I wrote a small function also...

:


#!/usr/bin/perl

# Count letter frequency.
# Infinite Recursion - 13 JUL 2006

use strict;

my $base = "this_is_a_test.txt";
my $count = CountUnderscore($base);

print "Number of _ is: $count\n";


sub CountUnderscore ($base)
{
    my @find = ('_');
    my %freq = ();

    foreach my $findc (@find)
    { 
        my $count = 0;
        foreach my $basec (split(//, $base))
        {     
            if ($basec eq $findc) 
            {         
                ++$count;
            }         
        }     

        $freq{$findc} = $count;
    } 

    return $freq{"_"};
}



[ir@grendel]# ./cfreq.pl
Number of _ is: 3


tbohon Jul 13th, 2006 10:23 AM

Thanks to both of you. Turns out that the value I was moving to $data was wrong ... should have checked that before posting I guess ... just too many things happening at once and too many 'break/fixes' on my plate.

Appreciate it!

Best,

Tom


All times are GMT -5. The time now is 12:44 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC