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

Hi

I'm using the following script to add multiple values to a hash

foreach $val (@array){

@tmp=split(/,/,$val);

push ( @{ $hash{$tmp 1 }}, $tmp[0]);

}

I want to sort that hash, and print only the values for the first keys

Replies are listed 'Best First'.
Re: hash first value
by FunkyMonk (Bishop) on Apr 10, 2008 at 15:15 UTC
    Sorted by key...
    my $count = 0; for ( sort { $a cmp $b } keys %hash ) { print "$_ => $hash{$_}\n" if $count++ < 10; }

    or by value...

    my $count = 0; for ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) { print "$_ => $hash{$_}\n" if $count++ < 10; }

    Assuming you want ascending order. Swap $a and $b inside the sord block if you want descending. Change the 10 to the number of "first" values you want

    If you had posted your code inside <code>...</code> tags, it would have been formated correctly.

    Update: See also How do I sort a hash (optionally by value instead of key)? in perlfaq4

    Update^2: Thanks to shmem for help with the link

Re: hash first value
by pc88mxer (Vicar) on Apr 10, 2008 at 15:45 UTC
    I want to sort that hash, and print only the values for the first keys
    Do you mean that for each key you want to sort the array associated with that key and then return the first (i.e. smallest value) in that array? If so, here's how to do that:
    my %smallest; for my $k (keys %hash) { my $v = (sort { $a <=> $b } @{$hash{$k}})[0]; # assuming numeric val +ues $smallest{$k} = $v; }
Re: hash first value
by Corion (Patriarch) on Apr 10, 2008 at 15:08 UTC

    You cannot sort a hash. You can only sort the hash keys. The function for sorting things is called, unimaginatively, sort.

    Where exactly do you have problems?

      Thats what i meant, sort has keys

      The probleme is how to print only the first value in the hash

        • Make a sorted list of keys.
        • print using the first of the keys.
        • Make that the last thing you do in your loop.
        • Profit!

        (Or simply use an array slice to pull off my $first_key = (sort keys %foo)[0] and just use that instead of setting up a loop . . .)

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

        So you want the first entry of the key/value set in your @array, where each entry in the @array is a comma separated list of key/val?

        my %hash = map { @_ = split /,/, $_; $_[0] => $_[1] } @array; my $first_key = (sort keys %hash)[0];

        You might not want to code it quite so compactly in a real app, but you should get the gist of it - turn into a hash, then take the first key from sorting the keys.

        Is that what you mean?