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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort hash ref values?

Status
Not open for further replies.

ericse

Programmer
Apr 19, 2007
32
US
Hello,

I was wondering if anyone could help me sort a hash by values.

Essentially my structure is this:

Code:
$hash = { id1 => { 'company' = value,
                   'units' = value,
                   'url' = value, },
          id2 => { 'company' = value,
                   'units' = value,
                   'url' = value, } };

I'd like to sort the entire hash to print in order of company value (alphabetically). Anyone help?
 
See if this helps:
Code:
my $href = { id1 => { 'company' => "Starbucks",
                      'units' => 10,
                      'url' => "[URL unfurl="true"]www.starbucks.com",[/URL] },
             id2 => { 'company' => "Microsoft",
                      'units' => 20,
                      'url' => "[URL unfurl="true"]www.microsoft.com",[/URL] }
            };

my @print_order = sort {uc($href->{$a}->{company}) cmp 
                        uc($href->{$b}->{company})} keys %{$href};

foreach (@print_order) {
    print "Name: " . $href->{$_}->{company} . " - ID: $_" . "\n";
}
 
Thank you. That makes sense. I'll let you know if it works :)
 
By the nature of hashes, they cannot be sorted on a permanent basis.
You may iterate the hash in a sorted fashion though, and in doing so, you may create an index for later perusal. The index would need to be regenerated however if any value in your indexed fields ('company' in your case) changes.
Code:
my %hash;
my @index;

$hash{id1}{company} = 'company1';
$hash{id1}{units}   = 'units1';
$hash{id1}{url}     = 'url1';
$hash{id2}{company} = 'company3';
$hash{id2}{units}   = 'units3';
$hash{id2}{url}     = 'url3';
$hash{id3}{company} = 'company2';
$hash{id3}{units}   = 'units2';
$hash{id3}{url}     = 'url2';

# Sort by company, and save the ordered keys into the index
push @index, $_ for sort ByCompany keys %hash ;

# run through the index ...
print "$_ = ".$hash{$_}{company}."\n" for @index ;

# Subroutine to sort the hash by company
sub ByCompany {	$hash{$a}{company} cmp $hash{$b}{company}; }
 
ok.
I shouldn't do this whilst working.
Day Late and a Dollar Short
 
:) Thanks guys. I have it working now. Appreciate the info.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top