Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Print Keys - values of two hashes in a tabulated fromat

by sesemin (Beadle)
on May 25, 2010 at 05:28 UTC ( [id://841476]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks,

How can I fix the following code (or may be rewrite) to print the keys and values of two hashes in a tabulated format. A simple operation also needed to be performed on values. The keys of two hashed are identical.

#! /usr/bin/perl -w use strict; my %hash_1 = ( 0.2 => '12', 0.4 => '13', 0.6 => '14', ); my %hash_2 = ( 0.2 => '19', 0.4 => '18', 0.6 => '20', ); foreach my $ObsKey ( sort { $a <=> $b } keys %hash_1 ) { foreach my $PermKey ( sort { $a <=> $b } keys %hash_2 ) { my $diff_obs_perm = $hash_1{$ObsKey}-$hash_2{$PermKey}; my $FDR = $hash_2{$PermKey} / $hash_1{$ObsKey}; my $currentdeltaprint = join ("\t", $ObsKey, $hash_1{$ObsKey}, $hash_2{$PermKey}, $diff_obs_perm, $FDR ); print "$currentdeltaprint\n"; } }

It seems I need to exit the inner loop after each printing. But it keeps printing until all the keys of the inner loop get exhausted and goes to the outer loop.

Thanks Monks.

Replies are listed 'Best First'.
Re: Print Keys - values of two hashes in a tabulated fromat
by bobf (Monsignor) on May 25, 2010 at 05:48 UTC

    Unless I am misunderstanding the problem, I don't think you need the inner loop at all. You only need to iterate over the list of keys once.

    If that doesn't produce the desired result, please clarify the problem.

    Update: Here is a modified version of your code (which may be more clear than my reply above).

    use strict; use warnings; my %hash_1 = ( 0.2 => '12', 0.4 => '13', 0.6 => '14', ); my %hash_2 = ( 0.2 => '19', 0.4 => '18', 0.6 => '20', ); foreach my $key ( sort { $a <=> $b } keys %hash_1 ) { my $diff_obs_perm = $hash_1{$key}-$hash_2{$key}; my $FDR = $hash_2{$key} / $hash_1{$key}; my $currentdeltaprint = join ("\t", $key, $hash_1{$key}, $hash_2{$key}, $diff_obs_perm, $FDR ); print "$currentdeltaprint\n"; }

      Thanks, I fixed it according to your recommendation. Then I saw the corrected code.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-25 12:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found