in reply to Simple hash problem

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.

Replies are listed 'Best First'.
Re: Simple hash problem
by Abigail-II (Bishop) on Oct 14, 2002 at 15:06 UTC
    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