Welcome to Dream.In.Code
Become an Expert!

Join 149,526 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,465 people online right now. Registration is fast and FREE... Join Now!




compare two hashes

 
Reply to this topicStart new topic

compare two hashes, comparison of the keys of two hashes

sasanthi
6 Jul, 2007 - 04:33 AM
Post #1

New D.I.C Head
*

Joined: 27 Dec, 2006
Posts: 12


My Contributions
Hey!!

I am trying to compare the columns of two files. I keep each column in a hash but they do not have the same length. My code is:

CODE

foreach (<FILE1>) {
    
    my $outer_text = $_;
    my @ar_id2 = split(/\t/,$outer_text);
    my $id = $ar_id2[0];
    $hash_id{$id} = $id;

}
    foreach (<FILE2>) {
        $inner_text = $_;
        my @array = split(/ /, $inner_text);
        $hash{$inner_text} = $array[0];
        
    }

        foreach my $key (keys %hash_id){
            if (defined $hash{$key}){
                print OUTFILE $key . "\n";
            }
        }
    

        

close OUTFILE;

close FILE1;
close FILE2;


There is no syntax problem, but it does not give to me any output. Could someone help me?

Thanks a lot!!
User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Compare Two Hashes
6 Jul, 2007 - 10:02 AM
Post #2

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
instead of "foreach" you should be using 'while" when reading from the filehandles.


CODE

# assumes all files are successfully opened for reading/writing
# assumes you do not need to chomp() the input data
# assumes your hashes are declared already and you are using "strict"

while (<FILE1>) {
   my @t = split(/\t/);
   $hash_id{$t[0]} = $t[0];

}

while (<FILE2>) {
   my @t = split(/ /);
   $hash{$_} = $t[0];
}

foreach my $key (keys %hash_id){
   if (defined $hash{$key}){
      print OUTFILE $key . "\n";
   }
}
close OUTFILE;
close FILE1;
close FILE2;


I also assume that the keys in %hash_id should be present in %hash because the foreach loop is printing the keys from %hash_id if there is a defined value of the same hash key in %hash.

Are looking for duplicate entries in two files?
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 08:46PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month