Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

perl - Compare two hashes by value to get keys/values where the 2nd is greater

I have code:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

#Coder: pavel69

open FILE1, "/home/stackovershroom/0/28.12.txt" or die;
my %dec28;
while (my $line1=<FILE1>) {
 chomp($line1);
 (my $plu28, my $count28) = split / /, $line1;
 $dec28{$plu28} = $count28;
}

open FILE2, "/home/stackovershroom/0/29.12.txt" or die;
my %dec29;
while (my $line2=<FILE2>) {
 chomp($line2);
 (my $plu29, my $count29) = split / /, $line2;
 $dec29{$plu29} = $count29;
}

print Dumper \%dec28;
print Dumper \%dec29;

Output:

     $VAR1 = {
     '3203100' => '7',
     '3467390' => '14',
     '3017931' => '19',
     '3312878' => '1.806',
     '3362576' => '56',
     '3173204' => '23',
     '3335495' => '6.377',
     '202' => '30.848',
     '2161067' => '13',
     '3356411' => '6',
     '3483437' => '6',
     '3359188' => '11',
     '...' => '...' #yet more 500 strings!
     };
    $VAR1 = {
     '3153446' => '89.480',
     '2062513' => '9',
     '3386209' => '8.379',
     '3195682' => '17.266',
     '3411129' => '18',
     '3154498' => '4.916',
     '2043226' => '12',
     '...' => '...' #yet more 500 strings!
     };

I want to compare two hashes for searching keys from %dec28, values of which were incremented (from %dec29).

For clarity, in %dec28 I have:

'209198' => '2'

in %dec29 I have:

'209198' => '13'

Need to get all (only) incremented values for %dec28 when compare %dec28 <=> %dec29 (Increment values contains in %dec29). I was only able to get new keys/values that occur in %dec29

Minimal example:

%dec28 = (
         '3091212' => '1',
         '2093334' => '74',
         '209' => '5.600',
         '1947754' => '3',
         '3130087' => '6');

%dec29 = (
         '3091212' => '4',
         '2093334' => '60',
         '209' => '13.844',
         '1947754' => '9',
         '3130087' => '6');

Need to construct new

%increment_values = (
         '3091212' => '4'
         '209' => '13.844'
         '1947754' => '9');

It is possible? How I can do it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand correctly, you want something like this:

# For each key in %dec28
for my $k (keys %dec28) {
  # If the same key exists in %dec29
  # And the %dec29 value is greater than the %dec28 value
  if (exists $dec29{$k} and $dec29{$k} > $dec28{$k}) {
    # Print something useful
    print "$k: $dec28{$k} -> $dec29{$k}
";
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...