Scott E Robinson wrote:

>Rob Hanson wrote:
>> You might be able to shorten this, but this seems to work ok...
>>
>> $x = ':B000:W000:M260:8:';
>> @y = $x =~ /:8:/g;
>> print scalar(@y);
>>
>> @y will contain the matches, one for each element of the array.
>> Grabbing the array in scalar context will get you the count of the
>> matches.  ...There is probably a faster way though, one that won't
>> require building the @y array.
>>
>> Rob
>>
>>
>>
>> -----Original Message-----
>> From: [EMAIL PROTECTED]
>> [mailto:[EMAIL PROTECTED]
>> Sent: Wednesday, March 12, 2003 2:58 PM
>> To: [EMAIL PROTECTED]
>> Subject: COunting the number of times a string matches in another
>> string
>>
>>
>> Hi!  Maybe this is really easy, but hey, I'm a beginner with Perl.
>>
>> I'm trying to count the number of times a string is contained inside
>> another string.  Here's a sample of my data, a set of colon-delimited
>> values from the Perl Soundex function, with a few pure numbers or
>> letters mixed in.
>
> Rob, thanks!  This might work, but can you tell me how to make the
> pattern (:8: in your example) a variable?  And I think I can count
> the number of
> elements in the @y array and use that as my match count, too.

Hello Scott.

Joseph's quite right, the problem isn't easy to fully grasp
from your description. I do know though that it's easy to
see only one interpretation of your explanation when you
know what it's supposed to mean :-) The solutions that you've
been offered using a hash table of frequencies assume that
you require and have available all of the data at thew same
time. It may be that you have only a single 'candidate' and
'target' pair at a time. I've tried to write something that
shows how you can approach the problem in general. It uses
your sample candidate and target strings and produces the
results that you said were correct. You should be able to
adjust it to suit your situation.

Come back if you have any questions.

Rob


#perl
use strict;
use warnings;

my @target = map { s/\s.*//s; $_ } <DATA>;
close DATA;

my $candidate = ':B000:W000:M260:8:';

foreach my $soundex ($candidate =~ m/\w+/g) {

    printf "%4s -", $soundex;

    foreach (@target) {
        my $count = @{[m/\b$soundex\b/g]};
        print " ", $count;
    }

    print "\n";
}

__DATA__
:L520:T400:C000:S000:L200:8:          <-bare numbers are possible, like
this :8:
:L520:T400:C000:S000:L200:8:
:L520:T400:C000:S000:L200:24:E214:
:L520:T400:C000:S000:M:24:E214:       <-note the :M: string, just for
variety
:L520:T400:C000:S000:L200:14:E214:
:L520:T400:C000:S000:L200:14:E214:
:L520:M260:C000:S000:L200:14:E214:    <-this should match once
:L520:T400:M260:S000:M260:14:E214:    <-this should match twice
:L520:T400:C000:S000:L200:14:E214:

output:

B000 - 0 0 0 0 0 0 0 0 0 0
W000 - 0 0 0 0 0 0 0 0 0 0
M260 - 0 0 0 0 0 0 1 2 0 0
   8 - 1 1 0 0 0 0 0 0 0 0




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to