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!
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};
...
}
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With