Link to home
Start Free TrialLog in
Avatar of jpcs
jpcs

asked on

sort an hash

Hi!

I have a hash structure like this

%data = (
   1 => {
      name => "Johnny",
      age => "21",
        },
   2 => {
      name => "Barney",
      age => "35",
        },
   3 => {
      name => "Mary",
      age => "18",
        },
   4 => {
      name => "Chris",
      age => "21",
        },
        );
            

I want to sort it by all names and ages, but I can't do that.

Please note that there are some ages equal.


By the way, how can I delete the entire "2" SubHash?



Thanks
Avatar of ozo
ozo
Flag of United States of America image

perldoc -q sort
Avatar of helver
helver

delete $data{2};
you should probably implement this is as an array, they're really just hashes 'keyed' by integers (and more efficient)
@data=( { name => "Johnny", age => "21"}, etc. );
note that the indicies start at 0
to sort this data by name you could do
@data = sort {$a->{name} cmp $b->{name} } @data;
or by age
@data = sort {$a->{age} <=> $b->{age} } @data;
since hashes aren't stored in any specific order i don't think the same thing could be accomplished with one sort function on your "hash of hashes" as it can with this "array of hashes"

to remove a hash entry:
delete $data{2}
sorry to repeate you helver, you answered while i was typing so i didn't see it
Avatar of jpcs

ASKER

Great!!!


Thanks you all, specially adam923. You solved my problem.


regards
ASKER CERTIFIED SOLUTION
Avatar of adam923
adam923

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial