in reply to Sorting a hash in one line

normal hashes have no order and can't be sorted!

But if you wanna get the values in a special order you can use a hashslice on sorted keys in one line

@svalues = @hash{ sort {...} keys %hash }

> But it gives error saying use of implicit split to @_ is deprecated.

scalar split has the ugly side effect to globber @_ (AFAIK at least prior 5.12), you may try something like m/(d)/ or tr/d// to count the "d"s.

UPDATE:

@svalues = @hash{ sort { $a=~tr/d// <=> $b=~tr/d// } keys %hash } should do.

even @svalues = @hash{ sort { $a=~tr/d// <=> $b=~tr/d// } %hash } does what you want (but I can't remember where it's documented) (was wrong)

Cheers Rolf

UPDATE: corrected typo, thx to davido

Replies are listed 'Best First'.
Re^2: Sorting a hash in one line
by ikegami (Patriarch) on Jun 21, 2010 at 08:17 UTC

    Sorting the list returned by %hash is quite wrong.

    use strict; use warnings; my %hash = map { $_ => 1 } qw( foo food dood ); my @svalues1 = @hash{ sort { $a=~tr/d// <=> $b=~tr/d// } keys %hash }; my @svalues2 = @hash{ sort { $a=~tr/d// <=> $b=~tr/d// } %hash }; print(0+@svalues1, "\n"); # 3 print(0+@svalues2, "\n"); # 6
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re^2: Sorting a hash in one line
by davido (Cardinal) on Jun 21, 2010 at 07:25 UTC

    Just a nit... but I would think "@svals" would be a more appropriate name for a variable holding values spit out from a hash slice, than "@skeys."


    Dave