How to get the first n key-value pairs from a hash table in Perl

I am very new to perl, so I searched for a while, but still get the answer. I want to get the first 100 pairs from a hash table, but I don’t know how to do it. To get each pair from a hash table, we can do something like:

foreach my $term (keys %hashtable) { do something regarding $hashtable{$term} here } 

But how to get the first 100 pairs out of it? Thank you very much!

+4
source share
3 answers

I'm new to Perl too, there may be a more elegant solution, but you can do the following:

 my $i = 0; foreach my $term (keys %hashtable) { ... do something regarding $hashtable{$term} here ... last if ($i++) == 100; } 
0
source

Another way:

 my %hash100 = (%hashtable)[0..199]; while ( my ($key, $value) = each %hash100 ) { ... } 

or

 for my $key ( (keys %hashtable)[0..99] ) { my $value = $hashtable{$key}; ... } 
+8
source

Note that there is nothing like the first 100 pairs of a hash, since the hash does not have a specific order.

Another solution that should protect your errors from one to one:

 for my $i (1 .. 100) { my ($key, $value) = each %hashtable; print "$key => $value\n"; } 
+7
source

Source: https://habr.com/ru/post/1442649/


All Articles