Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Quicker way to compare these 2 strings?

by Anonymous Monk
on May 19, 2010 at 00:07 UTC ( #840583=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow Monks!
I have 2 strings, namely:
$first= "AAAAXXXXAAAAXXXXXXXXXXXAAAA"; $second="AXXXAXXAAXXXXXAAAAXXXXXAAAA";

I want to know how many letters do they share in common. The "traditional" way that I'm thinking of is:
1) Split $first, split $second
2) Foreach letter in @split_first array, see if, in the same position in the array @split_second you have the same letter
3)Count the times you get success
Is there something quicker than that?
I just need the number of positions in the arrays (they always have the same number of letters), that the have the same letter.
Thanks!

Replies are listed 'Best First'.
Re: Quicker way to compare these 2 strings?
by TimToady (Parson) on May 19, 2010 at 00:57 UTC
    $matches = ($first ^ $second) =~ tr/\0//;
Re: Quicker way to compare these 2 strings?
by cormanaz (Deacon) on May 19, 2010 at 00:14 UTC
    You could do the same thing with substr without creating the arrays:
    my $matches; for my $i (0..length($first) { if (substr($first,$i,0) eq substr($second,$i,0)) { $matches++; } }
    I don't know if it would be faster, but it's possible since you wouldn't have the overhead associated with splitting the strings into the arrays. Maybe some interpreter monk knows the answer to that.
      I don't know if it would be faster, ... Maybe some interpreter monk knows the answer to that.
      No need to have intimate knowledge of the interpreter when the OP can just Benchmark the split solution versus your fine substr solution, using representative strings.
      Ok, with some minor corrections it works just fine!
      Thanks!
      $first= "AAAAXXXXAAAAXXXXXXXXXXXAAAA"; $second="AXXXAXXAAXXXXXAAAAXXXXXAAAA"; $matches=0; for $i (0..length($first)-1) { if (substr($first,$i,1) eq substr($second,$i,1)) { $matches++; } } print $matches."\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://840583]
Approved by cormanaz
Front-paged by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-08-17 20:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?