Gossamer Forum
Home : General : Perl Programming :

sort array

Quote Reply
sort array
evening,

I hope you can help me.

I've got the following hash:
Code:
%sort_results = ("$e_dat_name","$file");
I need to sort the above has so that it prints out the $e_dat_name in alphabetical order, but still keeps it associated with $file.

Does anyone have any tips on how to go about this?

I've exhausted myself for days now trying different sort routines, one of which ended up like this:

Code:
while (($sorte_dat_name,$sortfile,) = each(%sort_results)) {

$sortede_dat_name = sort { lc($sorte_dat_name{$a}) cmp lc($sorte_dat_name{$b}) }

%sorted_results = ("$sortede_dat_name","$sortfile");
}
But no joy. Can anyone please put me out of my misery?

Thankyou very much for your help.

Rgds,

Wiliam Stephens

Quote Reply
Re: sort array In reply to
First, you should write your hash as:

Code:
%sort_results = (
$e_dat_name => $file
);
If you are going to be having multiple pieces of the hash, writing it the above way will make it much more readable. And the quotes are not needed around the variables. Why interpolate when you don't have to?

Second. To sort... you just want to print out the keys in alphabetical order and print their valus with it?

Code:
print "$_ => $sort_results{$_}\n" foreach sort {$a cmp $b} keys %sort_results;

Installation support is provided via ICQ at UIN# 53788453. I will only respond on that number.
Quote Reply
Re: sort array In reply to
Thankyou, Mark.

I'll give your suggestions a shot.

By the way, what's the deal with importing hashes into another subroutine? Can you do that? I know you can get away with variables and arrays but I've never tried the old hash.

Rgds,

Wil.

Quote Reply
Re: sort array In reply to
Mark,

Bad news, the script you provided still doesn't print them out in alphabetical order for some reason.

Any more ideas?

Wil.