Date: 26 Jun 2001 16:39:13 GMT From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel) Subject: Re: how to sort array of similar hashes by one of the hash keys? Message-Id: <9hadrh$t7q$1@mamenchi.zrz.TU-Berlin.DE> According to Irfan Baig : > I've split data from a flatfile into hashes in an array, @game, all of > which have keys 'name', 'score' and 'date'. > > @game = (); > for ($i=0; $i<=$#scores; $i++){ ^^^^^^ This should be $#data, the array you loop over, not an array that happens to have as many elements. > ($game[$i]{'name'},$game[$i]{'score'},$game[$i]{'date'}) = split(/,/, > $data[$i]); > } I'll put aside the question why you first read the data into the array @data and then process each line. Surely you could process the lines directly from the file. You can avoid the use of an array index at the cost of another auxiliary variable: for ( @data ) { my %aux; # this *must* be declared inside the loop @aux{ qw( name score date) } = split /,/; push @games, \ %aux; } At the expense of some clarity an auxiliary can be avoided: @{ $game[ scalar @game]}{ qw( name score date)} = split /,/ for @data; Incidentally, this re-introduces index notation, but in a much more perlish way. > I'm now trying to sort the array by comparing the values of the 'score' elements > in each array's hash. Is this possible? I've tried some combinations such > as: > > @sorted_game = sort{ $game[$a]{'score'} <=> $game[$b]{'score'} } @game; Again, you are thinking of an array in terms of indexes. $a and $b aren't. They are array *elements*, in this case, complete hash references. You access the element you want directly via arrow- dereferencing: my @sorted_game = sort { $a->{ score} <=> $b->{ score}} @game; Anno