in reply to hash comparison

Perhaps this helps...Adjust the printout as you want...
I prefer "foreach" over "map" when there is no left hand value for the map.

#!/usr/bin/perl -w use strict; my $candidate = "the the the the the the the"; my $reference = "the cat is the on the mat"; my %cand_histogram; my %ref_histogram; $cand_histogram{$_}++ foreach (split(/\s+/,$candidate)); $ref_histogram{$_}++ foreach (split(/\s+/,$reference)); my %seen; printf "%-6s %-10s %-10s\n", 'Key','Candidate','Reference'; foreach my $key ( sort { $seen{$b} <=> $seen{$a} #descending word cnt or $a cmp $b #alphabetic otherwise } grep {!$seen{$_}++} # each key just once, # but count 'em also!, # 2 means => in both hashes (keys %cand_histogram, keys %ref_histogram) ) { printf "%-6s %-10s %-10s\n", $key, $cand_histogram{$key}||='0', $ref_histogram{$key} ||='0'; } __END__ OUTPUT: Key Candidate Reference the 7 3 cat 0 1 is 0 1 mat 0 1 on 0 1

Replies are listed 'Best First'.
Re^2: hash comparison
by sarvan (Sexton) on Jul 25, 2011 at 10:41 UTC
    Hi marshall, Thanks for the code..

    And one little modification i want to do on that.. Now it gives me all the words in both the candidate and reference and their counts.

    But the output i look for is, i want to know only minimum count of candidate words among both candidate and reference..

    for e.g if a word "the" appears 7 times in candidate and 2 times in reference. it should be able to get 2 as the min between two counts. like this for all the words in candidate alone..

    please give me an idea how to do this. I will try

    Thanks...
      Hi sarvan,
      I think that if you study the code, you will find that you have all that you need. The last "foreach" loop is on the fancy side of things, but it just loops over all of the unique keys in a special sort order. $cand_histogram{$key}||='0' uses 0 as the value in the case that there is no value for $cand_histogram{$key}. The print statement prints the 3 things that you need in order to calculate what you want. Why don't you give some code a try? Post your effort back here after you study it a bit.