Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Hash value sorting

by daxim (Chaplain)
on Aug 14, 2012 at 12:08 UTC ( #987334=note: print w/replies, xml ) Need Help??

in reply to Hash value sorting

perldoc -q sort: How do I sort a hash (optionally by value instead of key)?
foreach my $key ( sort { $self->{_counts}{$a} <=> $self->{_counts}{$b} } keys %{ $self->{_counts} } ) { printf "key %s: value %s\n", $key, $self->{_counts}{$key}; }

Replies are listed 'Best First'.
Re^2: Hash value sorting
by iHutch105 (Initiate) on Aug 14, 2012 at 12:26 UTC

    Awesome, sorted with one minor adjustment to your code; I had to dereference the conditions of the sort because it was sorting by the scalar reference address. I changed it to:

    foreach my $key ( sort { ${$self->{_counts}{$a}} <=> ${$self->{_counts}{$b}} } keys %{ $self->{_counts} }

    Thanks so much for the help.

      Try this:

      foreach my $key ( sort { $self->{_counts}->{$a} <=> $self->{_counts}->{$b} } keys %{ $self->{_counts} }

      If you do $self->{_counts}{$b}, Perl thinks $self->{_counts} is a real Hash, not an HashRef. If you use the arrow to dereference, it is easier to read.

      Take my advice. I don't use it anyway.
      That code collides with your explanation of the data structure in 987336. Only one can be correct.

      In the constructor I see you initialise the field _counts with a hash reference. Where do you now get a scalar reference from?

      It would help if you dump $self before sorting, so we can see what the data structure really looks like.

      use Data::Dumper; print Dumper $self;

        You're absolutely right and I've found the problem.

        I made a mistake whenever I was creating/adding to values in the hash. I had this line:

        ${$self->{_counts}{$key}} += $value;

        This was where the scalar ref was coming from. I should note, key and value are parameter passed in, representing the obvious. This line explains why I had to do some extra, dodgy dereferencing later on and, of course, should have read:

        $self->{_counts}{$key} += $value;

        All seems to be sorted now. Code looks a lot tidier too. First time I've really used references much but it's been a good learning experience.

        Thanks to all for the help and suggestions.

Re^2: Hash value sorting
by iHutch105 (Initiate) on Aug 14, 2012 at 12:16 UTC

    Thanks! It looks kind similar to what I have. Maybe I'm screwing up somewhere with the dereferencing. I'll give that a shot.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://987334]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2018-02-24 22:24 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (311 votes). Check out past polls.