Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a simple hash that I am looping through using a foreach statement but I would like to only loop through it "x" number of times. The foreach statement is as follows:

foreach $key (sort keys %user_hash) {

How can I go about this? I tried the following code, but as I am sure you are already aware, it didn't work.

foreach $key (sort keys %user_hash [0..$x]) {

What am I doing wrong?

Much thanks in advance.

Replies are listed 'Best First'.
•Re: Simple hash problem
by merlyn (Sage) on Oct 14, 2002 at 14:52 UTC
Re: Simple hash problem
by Joost (Canon) on Oct 14, 2002 at 14:48 UTC
    foreach $key ((sort keys %user_hash)[0 .. $x]) {
    Should do the thick, but it will build a seperate list of all the keys first that might take a lot of memory, which is not needed, especially if you only want a relatively small number of keys, so:

    foreach $key (sort keys %user_hash) { last if $key_count++ > $x; ... }
    will work a little more efficient.

    Update: Abigail is right, the problem is in the sorting. I don't know what the difference will be when you remove the sort from the first method though the second would certainly not take more elements than nessicary.

    -- Joost downtime n. The period during which a system is error-free and immune from user input.
      Really? How did you plan to do the sorting without building the list of all the keys?

      The problem isn't in the slicing (if it makes an impact, it's probably positive, as it reduces the size of the list Perl needs to keep track of as soon as possible), it's the sorting.

      Abigail

Re: Simple hash problem
by robartes (Priest) on Oct 14, 2002 at 14:57 UTC
    Or, yet another way:
    use strict; my %hash=("frog"=>"green", "camel"=>"camel_coloured", "flea"=>"who_kno +ws"); for (my $i=0,my @array=sort keys %hash; $i < 2 ; $i++) { print "Key $i: $array[$i]\n"; }
    However, merlyn's answer shines in its KISSiness, so you're best off going with his solution.

    CU
    Robartes-

    Update: Changed code snippet so it actually demonstrates the point made.