Gossamer Forum
Quote Reply
Sort
Hiya,

Any chance of some more advice? Can I pick on your wizdom for just a few seconds.

I have the following code (which doesn't work) to try and sort a has alphabetically according to the values.
Code:
# while (($myfile,$myname) = each %tobesorted) {
# print "$myfile => $myname<BR>";
# }
Does that make any sense to you? It would be nice to create a new has actually with the sorted values in them.

Any help would be appreciated.

Rgds,

Wiliam.

Quote Reply
Re: Sort In reply to
In reply to my own message. I have dvised the following line:

sort { lc($tobesorted{$b}) cmp lc($tobesorted{$a}) } (values %tobesorted);

and that doesn't work. Nothing seems to sort my hash table :-(

Any suggestions?

Wil.

Quote Reply
Re: Sort In reply to
I suggest learning more about Perl's looping ability.

print "$_ => $tobesorted{$_}<BR>\n" for sort keys %tobesorted;

-- Gordon


s/(\d{2})/chr($1)/ge + print if $_ = '8284703280698276687967';
Quote Reply
Re: Sort In reply to
That sorts by keys.. to sort by values you need to pass in a sort function like he had. Something like:


foreach my $key (sort { lc $hash{$a} cmp lc $hash{$b} } keys %hash) {
.. # sorted by value
}

Cheers,

Alex

--
Gossamer Threads Inc.
Quote Reply
Re: Sort In reply to
Ahh, my error. Should have read the 'values' part shouldn't I?;)

So then, to follow my original post, try:

print "$_ => $tobesorted{$_}<BR>\n" for sort {lc $tobesorted{$a} cmp lc $tobesorted{$b}} keys %tobesorted;


-- Captain Oversight


s/(\d{2})/chr($1)/ge + print if $_ = '8284703280698276687967';
Quote Reply
Re: Sort In reply to
Tried both of your suggestions.

I would like to use Alex's approach because that would allow me to sort the hash and then I could export the hash into another sub-routine.

But, the sorting piece of code you gave me doesn't seem to work either. Any clues?

I have the following pieces of lines:

Code:
if ($field =~ /$term/ig) {
$tobesorted{$file} = $e_dat_name;

&print_results(%tobesorted);
Now I need to sort inbetween building the hash and exporting it to the next sub-routine.

Any help would be appreciated.

Thankyou!

Wil.