Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Perl hash comparison

by robertw (Sexton)
on Aug 16, 2012 at 20:11 UTC ( [id://987870]=perlquestion: print w/replies, xml ) Need Help??

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

Dear Perlmonks, I have this huge hash that contains many five character keys, I want to make a subroutine that: if i give it for example two characters will foreach hash key calculate how many percent matches: if 1 character is in the hash key it is 1/5, with two it is 2/5 and multiply that number with the number associated with the hash key it has that many percent match with. Does anybody know how I could build such a thing or give helpful advice:)? Thank you so much in advance.

Replies are listed 'Best First'.
Re: Perl hash comparison
by Kenosis (Priest) on Aug 17, 2012 at 00:25 UTC

    Perhaps I'm misunderstanding your issue's description, but it sounds like the following: given a set of characters and a hash key, return (chars in key / 5) * $hash{key}. If this is the case, perhaps the following will work for you:

    use Modern::Perl; my %hash = ( ABCDE => 12, FGHIJ => 7, KLMNO => 2 ); say getMatchResult( 'AC', 'ABCDE' ); sub getMatchResult { my ( $find, $key ) = @_; my $matches = () = $key =~ /[$find]/ig; ( $matches / 5 ) * $hash{$key}; }

    Output:

    4.8

    Hope this helps!

    Update: Thanks to hmb for suggesting the goatse operator (and character class). It timed faster than my iterative solution w/regex.

      #my $matches; #$matches += $key =~ /$1/i while $find =~ /(.)/g; # or the "rolex" operator! my $match =()= $key=~/[$find]/ig;

        This is a good suggestion; I'll make the change in the script.

Re: Perl hash comparison
by Anonymous Monk on Aug 16, 2012 at 20:14 UTC
    Have you heard of keys? Any more questions?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-03-28 19:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found