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


the goal: want check if entries in hash equal in manner (here it's count).

my nasty solution:

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

i know store size in first iteration of loop, not need key in advance. cause me conditional statement in eacht iteration. avoid it.

the question: proper way key hash?

addition: there should possible (keys %hash)[0]

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

my ($key) = keys %hash; 

another way use each in scalar context:

my $key = each %hash; 

in testing loop, interested in values, don't iterate on keys, too:

for $arr_ref (values %hash) { 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -