Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help with this sort from someone heavier than me 2

Status
Not open for further replies.

ejaggers

Programmer
Feb 26, 2005
148
US
by_hashvalue works fine, but can someone please explain how it works? I would like to rewrite it with no global variables, but everything I try breaks it.
I have “my %names” in main, but by_hashvalue sees it, and I don’t have a clue why. I need by_hashvalue to sort any hash, not just %names.

# Sort hash by value then by key.
my %names = (
1 => 'evan',
2 => 'sam',
3 => 'evan',
4 => 'joyce',
5 => 'sam',
6 => 'monster');

my @hashkeys = sort by_hashvalue(keys(%names));
foreach $key (@hashkeys) {
print "$key - $names{$key}\n";
}
sub by_hashvalue {
return ( $names{$a} cmp $names{$b} ) || ($a cmp $b);
}
 
Your question and your description are hard to follow. You say you have %names in main, but it appears all of your code is in main, so that has no relevance. Your code is sorting the hash keys by the values first, and then by the keys if necessary. If you can clarify your question maybe someone can help clear up whatever your confusion is.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
All of my code is Not in main. You must have missed:
"sub by_hashvalue {
 
huh? Someones confused or not explaining themself very well. "sub by_hashvalue {" is just a custom sort function but its still in main unless you demonstrate otherwise.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I find it difficult to understand what you are trying to achieve but in answer to your last point "need by_hashvalue to sort any hash, not just %names", I think that you could make use of references. Pass a reference of %hash_name into $hashref (my $hashref = \%names;) each time you want to refer to a hash table, or create an array of hash references.
Heres an example using your methods:

Code:
my $hashref = \%names;
my @hashkeys = sort by_hashvalue(keys(%{$hashref}));
foreach my $key (@hashkeys){
	print "$key - $$hashref{$key}<br>";
}
sub by_hashvalue{
	return($$hashref{$a} cmp $$hashref{$b} ) || ($a cmp $b);
}

Chris

 
To sort the way you're talking about, you'll need to use references. Something like this might work for you:
Code:
my @hashkeys = sort_hash_by_val(\%names);
foreach my $key (@hashkeys) {
	print "$key - $names{$key}\n";
}

sub sort_hash_by_val {
	my $href = shift;
	my @temp = sort {$href->{$a} cmp $href->{$b} || $a <=> $b} keys %$href;
	return @temp;
}
 
Thanks rharsh,

That was exactly what I needed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top