Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find minimum and maximum value for a hash value in perl

I have a hash which stores strings as keys and their occurrence as values.

$VAR1 = {
          'ABCD' => 2,
          'EFGH' => 7,
          'IJKL' => 17,
          'MNOP' => 2,
           'OPMN' => 300,
           'QRST' => 300,
           'DEAC' => 300

}

I want to find minimum and maximum of the values for this hash. Eg min = 2 and max = 300

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried following code which gave error Can't use string ("17") as an ARRAY ref while "strict refs" in use at

$minAssigned = min(@{$countPat{$pat4C}});

$maxAssigned = max(@{$countPat{$pat4C}});

How can I resolve this error. Also once I have these numbers I want to loop through the values of the same hash minAssigned to maxAssigned times and print the total occurrence of the values. For example the value 2 occurs 2 times, Value 17 occurs 1 time, value 300 occurs 3 times.

Appreciate any help in advance !

>Solution :

Use values to get the list of hash values.

#!/usr/bin/perl
use warnings;
use strict;

use List::Util qw{ min max };

my $h = {
          'ABCD' => 2,
          'EFGH' => 7,
          'IJKL' => 17,
          'MNOP' => 2,
          'OPMN' => 300,
          'QRST' => 300,
          'DEAC' => 300

};

print min(values %$h), "\n";
print max(values %$h), "\n";

Use another hash to count the frequencies:

my %freq;
++$freq{$_} for values %$h;
for my $k (keys %freq) {
    print "$k occurs $freq{$k} times.\n";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading