Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hash

perl

I'm very new to perl so I searched for some time but still get the answer. I want to get first 100 pairs from a hash table but don't know how to do that. 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 first 100 pairs out of it? Thanks a lot!

like image 664
Iam619 Avatar asked Dec 06 '22 11:12

Iam619


2 Answers

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};
    ...
}
like image 198
ysth Avatar answered Dec 28 '22 22:12

ysth


Note that there is nothing like the first 100 pairs from a hash since a hash has no particular order.

Another solution that should protect your from off-by-one errors:

for my $i (1 .. 100) {
    my ($key, $value) = each %hashtable;
    print "$key => $value\n";
}
like image 27
choroba Avatar answered Dec 29 '22 00:12

choroba