Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of entries in a hash with values less than n?

Tags:

hashmap

perl

Below I use $size = keys %prices; to get the total number of entries in a hash. However, is there a way in the example below to get the number of entries with price less than $4?

use strict;

my %prices;

# create the hash
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;
$prices{'pie'} = 6.50;
$prices{'coffee'} = 2.50;
$prices{'churro'} = 2.25;

# get the hash size
my $size = keys %prices;

# print the hash size
print "The hash contains $size elements.\n";
like image 771
gatorreina Avatar asked Oct 22 '21 20:10

gatorreina


Video Answer


2 Answers

Yes, you can run a grep filter on the values of the hash to quickly calculate this.

 $num_cheap_items = grep { $_ < 4 } values %prices;
 @the_cheap_items = grep { $prices{$_} < 4 } keys %prices;
like image 194
mob Avatar answered Oct 28 '22 00:10

mob


Yes, you can loop through the keys of the hash and check if each value is less than 4:

my $num = 0;
for (keys %prices) {
    $num++ if $prices{$_} < 4;
}
print "less than 4: $num\n";

Prints:

The hash contains 6 elements.
less than 4: 4
like image 25
toolic Avatar answered Oct 28 '22 01:10

toolic