[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 160
  • Last Modified:

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
0
jpcs
Asked:
jpcs
1 Solution
 
ozoCommented:
perldoc -q sort
0
 
helverCommented:
delete $data{2};
0
 
adam923Commented:
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}
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
adam923Commented:
sorry to repeate you helver, you answered while i was typing so i didn't see it
0
 
jpcsAuthor Commented:
Great!!!


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


regards
0
 
adam923Commented:
you're welcome
0

Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now