On Aug 21, 2012, at 1:05 PM, Chris Stinemetz wrote:
> Hello List,
>
> I am trying to sort a hash of arrays ( example below: )
>
> I would the sort to sort in ascending order the first index of the array
> then the second index of the array.
I believe you mean "first element" rather than "first index". The first index
of your array is 0, and sorting by the indices is a no-operation.
What you want to do is sort the list of keys returned by the keys() function.
You do this by supplying a subroutine reference to the sort function that
returns a negative value, zero, or a positive value if the first key yields a
value less than, equal to, or greater than the value produced by the second
key. The user-supplied sort function is provided the two keys as the variables
$a and $b.
If you want to sort by the first element of the arrays referenced by the hash
values, then you want the values $a->[0] and $b->[0]. Since in your case, these
values are numbers rather than strings, you want to use the tri-level <=>
operator (rather than the cmp operator used for strings.)
Thus the expression
sort { $a->[0] <=> $b-{0] } keys %hash;
should return the keys in your desired order.
If you want to include a secondary key, you evaluate an expression that
compares another array element if the first array elements are equal. This
expression will do that;
$a->[0] <=> $b->[0] ||
$a->[1] <=> $b->[1]
I will leave it to you to write an actual program incorporating these ideas.
If you want to test your two-key sort, you will need to include some test data
in which two or more records have the same first element.
>
> So in this example the arrays would sort to:
>
> 97,2,120,65
> 219,1,30,33
> 280,3,230,90
> 462,2,270,65
>
> $VAR1 = {
> '462-2' => [
> '462',
> '2',
> '270',
> '65'
> ],
> '219-1' => [
> '219',
> '1',
> '30',
> '33'
> ],
> '280-3' => [
> '280',
> '3',
> '230',
> '90'
> ],
> '97-2' => [
> '97',
> '2',
> '120',
> '65'
>
> };
>
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/