develooper Front page | perl.beginners | Postings from February 2002

Re: sort on anonymous array elements as hash values

Thread Previous | Thread Next
Michael Lamertz
February 6, 2002 09:00
Re: sort on anonymous array elements as hash values
Message ID:
On Wed, Feb 06, 2002 at 05:35:44PM +0100, birgit kellner wrote:
> my %hash = (
> 	'keyone' => ['firstvalueone', 'firstvaluetwo],
> 	'secondkey' => ['anothervalueone', 'valuetwoforsecondkey'],
> 	'keythree' => ['thirdvalueone', 'thirdvaluetwo']
> );
> Can I sort the hash on the second element of the anonymous array?

The hash itself cannot be sorted, since it's a hash, not a list.
However, you can store the keys of the hash in a list that's sorted by
your criteria:

    ---------- snip ----------
    my @order=sort { $hash{$a}[1] cmp $hash{$b}[1] } keys %hash;
    print @order;
    ---------- snip ----------

'perldoc -f sort' to find out about codeblocks in the sort command.
Basically, 'sort' needs a compare function.  That function knows two
parameters '$a' and '$b' and returns their relation (perldoc -f cmp).

Internally, I believe 'sort' then does a qsort, calling your provided
comparism-code each time it has to decide what to do next.

The result is the ordered list of hash-keys.

> Output should be:
> firstvaluetwo
> thirdvaluetwo
> valuetwoforsecondkey

Ah, you don't want the hash sorted, but only the ordered values of the
2nd column?

Similar procedure:

    ---------- snip ----------
    print sort map { $_->[1] } values %hash;
    ---------- snip ----------

1st: 'perldoc -f values', 'perldoc -f map'.

'values %hash' gives you a list that contains all right-side parts of
the hash

    print values %hash;



Not very helpful, but that's how your array-references look from the

Now, the 'map' acts kind like a filter, applying some code to each
element of a list and returning a new list that contains all the results
of that codeblock.  The codeblock gets its parameters via $_, thus
'$_->[1]' means 'on each value of %hash give me the 2nd array element.

Then that list is then put into sort - you have read 'perldoc -f sort'
by now, haven't you?

Hmmmm, did I make sense?

                     If we fail, we will lose the war.

Michael Lamertz        |                            
    Nordstr. 49        | -
    50733 Cologne      |                               Priv:    +49 221 445420
    Germany            |                             Mobile:  +49 171 6900 310

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About