Spartacus
Spartacus

Reputation: 25

Is there a way to count hash values that are also elements of an array?

I have an array of elements (@codes) and some of these elements are values in a hash (%records), however the hash also has values that are not contained in the array (@codes).

Is there a way to count the number of hash keys from %records where the corresponding hash value is an element of the array @codes? I'd like to do this without iterating through a loop if possible. Thanks!

Upvotes: 0

Views: 201

Answers (1)

Sobrique
Sobrique

Reputation: 53478

As an example of how you'd do this with map:

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

my %records = (
    'one'   => 1,
    'two'   => 2,
    'three' => 3,
);

my @codes = ( 'one', 'three', 'fake' );

my %seen = map { $_ => 1 } @codes;
print scalar grep ( $seen{$_}, keys(%records) );

But don't be under any illusions - this is still doing a loop, it's just implicit in the map function.

Upvotes: 1

Related Questions