raisputin has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I have a hash that looks like this:

username@domain->EMLIST->[emailaddress1,emailaddress2,emailaddress3] username@domain->COUNT->3 username24@domain->EMLIST->[ emailaddress1...emailaddress100 ] username24@domain->COUNT->100

I need to print it out to look something like

username24@domain, 100 ... username@domain, 3

I can print it with (readily available online of course)

while ( my ($key, $value) = each(%HASH) ) { print "<td>$key</td><td>$HASH{$key}->{COUNT}</td><tr>\n"; }
I also understand that I will need to sort the hash by the 'count' but I am totally lost on how to do that to say the least...I am sure it is easier than my brain is letting it be...

I will keep messing around with it here and hppefully figure it out, but ... any help appreciated :)

Replies are listed 'Best First'.
Re: Hash help
by ikegami (Patriarch) on Nov 03, 2009 at 19:27 UTC

    You need to get the entire hash contents at once if you want to sort them, so you can't use each.

    use HTML::Entities qw( encode_entities ); for my $id ( sort { $HASH{$a}{COUNT} <=> $HASH{$b}{COUNT} } keys(%HASH) ) { print "<tr>", "<td>", encode_entities($id), "</td>", "<td>", encode_entities($HASH{$id}{COUNT}), "</td>", "</tr>\n"; }

    I also fixed the bug where you were treating plain text as HTML.

    Swap $a and $b if you want to sort in descending order.

Re: Hash help
by roboticus (Chancellor) on Nov 03, 2009 at 19:32 UTC
    raisputin:

    The sort function will accept a chunk of code to define the sort order. So you should be able to tell sort to compare the value of the COUNT member of your hash using something similar to:

    for my $key (sort { $HASH{$a}{COUNT} <=> $HASH{$b}{COUNT} } keys %HASH +) { my $value = $HASH{$key}; ... }

    Caveat: I don't recall ever using this myself, I'm just parroting (correctly, I hope!) other posts I've seen here on how to do it.

    Caveat 2: You'll want some error checking for missing COUNT members, etc.

    Update: ... must learn to type as fast as ikegami ...

    ...roboticus
Re: Hash help
by GrandFather (Saint) on Nov 05, 2009 at 05:57 UTC

    Note that $hash->{username@domain}{EMLIST} is a reference to an array which you can access as @{$hash->{username@domain}{EMLIST}}. Therefore $hash->{username@domain}{COUNT} is very likely redundant because @{$hash->{username@domain}{EMLIST}} == $hash->{username@domain}{COUNT} and if it doesn't then there is most likely a bug in the code!

    It's generally a bad idea to keep two copies of the same information because they are likely to get out of sync. Because it is trivial to find out how many elements are in an array keeping a separate count is redundant and error prone.


    True laziness is hard work
Re: Hash help
by raisputin (Scribe) on Nov 03, 2009 at 20:06 UTC
    Thanks guys. Worked like a charm... :)