views:

848

answers:

3

Hey I was just wondering if there is a cool "one liner" that would sort my hash holding array references. So I have a bunch of key/values in my hash something like:

$DataBase{$key} = \@value;

However I would like to sort the hash by the array[0] element. Then loop through 'em. I had this to begin with:

foreach my $key (sort {$DataBase{$a} cmp $DataBase{$b} } keys %DataBase)

But that obviously just sorts my hash by the pointer value of the array. It doesn't exactly have to be "one line" but I was hoping for a solution that didn't involve reconstructing the hash.

+7  A: 
foreach my $key (sort {$DataBase{$a}->[0] cmp $DataBase{$b}->[0] } keys %DataBase)
chaos
Thanks, sorry for the newbish question... Just started with perl and didn't know i could use the -> operator!
Balk
Should work without the indirections, too, I just like them there because I'm a pedant.
chaos
@Balk: Ah, yeah, it's the 'nice' way of accessing references (as opposed to like @{$value}).
chaos
The -> is optional between two {}/[] things. See http://perlmonks.org/?node=references+quick+reference
ysth
+2  A: 

For the record (you probably come from a C background), Perl does not have pointers, but references:

Perl [...] allows you to create anonymous data structures, and supports a fundamental data type called a "reference," loosely equivalent to a C pointer. Just as C pointers can point to data as well as procedures, Perl's references can refer to conventional data types (scalars, arrays, and hashes) and other entities such as subroutines, typeglobs, and filehandles. Unlike C, they don't let you peek and poke at raw memory locations.

Similar, but not the same.

C.

Another difference is that you can ask a reference what type of thing it refers to with ref or Scalar::Util::reftype.
Chas. Owens
+1  A: 

I think you are asking the same basic question as How can I sort a hash-of-hashes by key in Perl?. My answer, which is in the Perl FAQ, shows you how to sort a hash any way that you like.

brian d foy