CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Sorting an array of hashes

 



JonnyThunder
User

Jul 6, 2002, 3:25 AM

Post #1 of 2 (333 views)
Sorting an array of hashes Can't Post

 
I've got an array of hashes (as read in from a file). Is it possible to sort this array of hashes on any of the elements in the hash?

My code...


Code
$memberfile         =   "user.dat"; 
open(FILE,"$memberfile") || die "Couldnt open $memberfile for reading";
@filecontent = <FILE>;
close(FILE);


# Process members list into array of hashes
for $index (0 .. $#filecontent) {
@currentline = split(/\|\|/, $filecontent[$index]);
$userdata[$index] = { 'userID' => $currentline[0],
'userSTAT' => $currentline[1],
'userNAME' => $currentline[2],
'userEMAIL' => $currentline[3],
'userPASS' => $currentline[4]};
}


For instance, if I wanted to sort on the userNAME field?
Also, is their an easier way or processing my data into the array of hashes other than I've done here? I spent ages this morning trying to figure out a 'smart' way of doing it!

:)


davorg
Thaumaturge / Moderator

Jul 6, 2002, 6:54 AM

Post #2 of 2 (331 views)
Re: [JonnyThunder] Sorting an array of hashes [In reply to] Can't Post


Code
my @sorted = sort { $a->{userNAME} cmp $b->{userNAME} } @userdata;

And similarly for any other data item.


In Reply To
Also, is their an easier way or processing my data into the array of hashes other than I've done here? I spent ages this morning trying to figure out a 'smart' way of doing it!


Firstly, I'd use "push" and do away with the need for $index. And I'd also process the file a line at a time rather than reading it all in at once.

Code
my $memberfile = "user.dat";  
open(FILE, $memberfile) || die "Couldnt open $memberfile for reading: $!";

my @userdata;
# Process members list into array of hashes
while (<FILE>) {
my @curr = split /\|\|/;
push @userdata, { 'userID' => $currentline[0],
'userSTAT' => $currentline[1],
'userNAME' => $currentline[2],
'userEMAIL' => $currentline[3],
'userPASS' => $currentline[4]};
}
close FILE;

But if I wanted to be really clever, I'd use a hash slice to do the assignment.

Code
my $memberfile = "user.dat";  
open(FILE, $memberfile) || die "Couldnt open $memberfile for reading: $!";

my @userdata;
my @cols = qw(userID userSTAT userNAME userEMAIL userPASS);
# Process members list into array of hashes
while (<FILE>) {
my %curr;
my @curr{@cols} = split /\|\|/;
push @userdata, \%curr;
}
close FILE;


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives