Bodo
Bodo

Reputation: 172

Perl: check in hash if all entries are equal, get an arbitrary/random key from hash

The goal: I want to check if all entries in a hash are equal in some manner (here it's the count).

My nasty solution:

# initialize some fake data
my @list1 = (2, 3);
my @list2 = (1, 2);
my %hash = (12 => \@list1, 22 => \@list2);
# here starts the quest for the key
my $key;
foreach my $a (keys %hash) {
  $key = $a;
}
# some $key is set
# here starts the actual comparision
my $count = scalar(@{%hash{$key}});
foreach my $arr_ref (%hash) {
  my $actcount = scalar(@$arr_ref);
  print "some warning" if $actcount != $count;
}

I know I could also store the size in the first iteration of the loop, then I would not need to get the key in advance. But it will cause me a conditional statement in eacht iteration. Thus I like to avoid it.

The question: What is a proper way to get a key from the hash?

Addition: There should be something possible like (keys %hash)[0]

Upvotes: 0

Views: 118

Answers (1)

choroba
choroba

Reputation: 242373

my $key = (keys %hash)[0] should work, or you can force list context by enclosing the scalar you assign to in parentheses:

my ($key) = keys %hash;

Another way would be to use each in scalar context:

my $key = each %hash;

In the testing loop, you are only interested in values, so don't iterate over the keys, too:

for my $arr_ref (values %hash) {

Upvotes: 1

Related Questions