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

Re: sort on anonymous array elements as hash values

Thread Previous | Thread Next
From:
Michael Lamertz
Date:
February 6, 2002 09:00
Subject:
Re: sort on anonymous array elements as hash values
Message ID:
20020206175928.GA31438@media-support.de
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;

gives

    ARRAY(0x80f60ac)
    ARRAY(0x8102f24)
    ARRAY(0x8102edc)

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

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        |                                      mike@lamertz.net
    Nordstr. 49        |     http://www.lamertz.net - http://www.perl-ronin.de
    50733 Cologne      |                               Priv:    +49 221 445420
    Germany            |                             Mobile:  +49 171 6900 310

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About