Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: string comparison

by robartes (Priest)
on May 27, 2005 at 07:16 UTC ( #460965=note: print w/replies, xml ) Need Help??

in reply to string comparison

Here's one, naieve and probably inefficient, solution:

#!/usr/local/bin/perl -w use strict; my @strings=("~cake,pastry","pastry,~cake","cake,pastry"); foreach my $i ( 0..2 ) { for ( 0 .. 2) { next if ( $i == $_ ); my %left=map { $_ => 'nevermind' } split /,/,$strings[$i]; my %right=map { $_ => 'nevermind' } split /,/,$strings[$_]; for (keys( %left )) { delete $left{$_} if exists $right{$_}; } print "String $i matches $_!\n" unless ( keys %left || keys %right + ); } } __END__ Output: String 0 matches 1! String 1 matches 0!

Never mind the inefficient loop within loop within loop. The important bit to this method is splitting the strings into a hash, then walking over one hash and deleting the keys that exist in the other. If anything is left, the strings do not match.

One quick optimisation is to immediately stop and declare inequality when you find that a key in one hash does not exist in the other - that will save you iterating over the entire hash in the worst case.

Update: Check both hashes after delete step. See reply to this post from whatluo as to why. Note that the more efficient solution to this would be as whatluo suggests -- report inequality when the number of keys does not match between the two hashes before going into the delete loop. The solution I offer leaves the differing keys in the hashes, so you can do something with them.


Replies are listed 'Best First'.
Re^2: string comparison
by whatluo (Novice) on May 27, 2005 at 09:18 UTC

      You're right - thanks. I've updated my code to check both hashes for leftover keys, which should catch that problem.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://460965]
[Corion]: $/ = "wahtever";
[Corion]: (it's a magic variable)
[karlgoethebier]: BarApp: whoami
[Cosmic37]: ok fankyou - I was wondering about that but thought there might be a redefine command or something; peachy
[Lotus1]: Cosmic37 if you undef $/ in a local context to a block it won't affect the global version after the block finishes
[Lotus1]: or you can just do local $/ in a block
[erix]: cool

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2017-06-29 16:50 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (673 votes). Check out past polls.