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

ye's all.

I'm trying to sort my hash with a series of different sorts. this is the code i'm using it seems to work. first, its sorts my list alphabetically then numerically by the number in {tag}.
foreach my $server ( sort {$my_server_hash {$a} cmp $my_server_hash {$ +b} && $my_server_hash{$a}{tag} <=> $my_server_hash{$b}{tag} } keys %my_server_hash)
to this i want find a string in  $my_server_hash{$server}{ADMINS} and drop that/them "record"s to last if a match is obtained; then finally - any 53s in the  $my_server_hash{tag} "records" need to be dropped to last.

i know i need to tidy up my code.

I have spent ages looking in books and websites but i am unable to find any code samples that i can get my head around.

can anyone offer any direction and/or some sample code to get me started?

this is a link to the output i'm trying to format..

i have me data, i just want it to look nice! thanks and good day.

C,.

Replies are listed 'Best First'.
Re: hash sort problems
by graff (Chancellor) on Apr 18, 2002 at 07:31 UTC
    You will probably be better off breaking the problem into two operations: first do the sort that you have now, but put the sorted keys into an array:
    @first_sort = (sort { .... } keys %my_server_hash );
    Once that's done, now partition the array into separate bins, which you can then use to print your whole set in whatever order you want. (Who knows, maybe next week you'll want the admins to be listed at the top instead of the bottom...) Pseudo-code example:
    for (@first_sort) { if ( &goes_first( $my_server_hash{$_} )) { push( @topset, $_ ); } elsif ( &goes_second( $my_server_hash{$_} )) { push( @set2, $_ ); # more steps if you want... } else { push( @lastset, $_ ); } } # now go through those subset arrays and print them in turn; # alpha-sorting is preserved within each subset...
    I'm sure obfuskaters would love to try cramming it all into a single monster sort block, but you might find it more maintainable if your priorities are stated explicitly.
Re: hash sort problems
by jarich (Curate) on Apr 18, 2002 at 05:32 UTC
    Hi Conal.

    I can't imagine what you're trying to solve at the moment, and your link doesn't make it clearer - to me anyway. I suspect you want to sort a hash alphabetically and then perhaps upon various parts of it's value.

    I tried your code:

    my %server_hash = ( foo => {tag => 1}, bar => {tag => 10}, boot => {tag => 2}, snow => {tag => 8}, fish => {tag => 3}, adv => {tag => 1} ); foreach my $server ( sort {$server_hash{$a} cmp $server_hash{$b} && $server_hash{$a}{tag} <=> $server_hash{$b}{tag} } keys %server_hash) { print "$server:$server_hash{$server}{tag}\n"; }
    and it gave me:
    foo:1 adv:1 boot:2 fish:3 snow:8 bar:10
    So I don't think that that's really what you're trying to do. Remember that you won't have several keys in the hash having the same value. Hashes don't do that.

    How about you give us a sample hash? And the desired result: a list of sorted keys? If you do just want to sort the hash alphabetically, then you're almost there.

    Jarich

Re: hash sort problems
by kappa (Chaplain) on Apr 18, 2002 at 11:59 UTC
    The:
    $my_server_hash {$a} cmp $my_server_hash {$b} && $my_server_hash{$a}{tag} <=> $my_server_hash{$b}{tag}
    piece most likely doesn't do what you you think it should.

    $my_server_hash{$a} evaluates to a hashref, doesn't it? So cmp compares two stringified hashrefs, and that doesn't make much sense.

Re: hash sort problems
by ferrency (Deacon) on Apr 18, 2002 at 15:40 UTC
    I'm not exactly sure what you're trying to do here, but I think you might want to use a standard technique for sorting on multiple fields:

    sort {$a cmp $b or $hash{$a} cmp $hash{$b}} keys %hash;
    This first compares $a vs. $b. If they're equal, then it falls back to comparing $hash{$a} against $hash{$b}. Your code is using an && instead of || or "or". I don't understand what that's for.

    However, in the example I just gave, the secondary comparison is useless, because a hash always has unique keys. Therefore, the second part of the "or" clause will never be evaluated.

    I'm not sure why you're comparing $my_server_hash{$a} vs $my_server_hash{$b}, because these are apparently hash refs, which don't compare in any useful way.

    If you give more info on the format of the data in your hash (as opposed to what it looks like once you render it in html) we might be able to give you more useful help.

    Alan

Re: hash sort problems
by Conal (Beadle) on Apr 19, 2002 at 00:41 UTC
    Thanks folks for all your replies! its really made my day!

    as you've probably guessed its some of the concepts i'm struggling with.

    what this code does below seems to do is sort my hash by key alphabetically it then (i think) sorts by the value in {tag} which groups all the records which have the same value in {tag} together for me.

    I want to add another 2 sorts.

    1. I want to be to pick out a value(53) in {tag} and group my records by that, which will be processed by the foreach loop last so it becomes the last lines in my HTML output.

    2. The last group/sort of my hash is pick out this condition in $my_server_hash{$server}{ADMINS} =~ s/$account/FOUND:; and group all those trues togther and make this the second last lines in my HTML.

    I include a sample hash.

    my %server_hash = ( SERVER1 => {tag => 53, ADMINS => undef, ADMINSGRP += undef}, SERVER2 => {tag => 1, ADMINS = "account1", ADMINSGRP = ["gl +obal1","global2"]}, SERVER3 => {tag => 1236 ADMINS = "account2", ADMI +NSGRP = ["global1","global2"]}, SERVER4 => {tag => 1236 ADMINS = "acc +ount1", ADMINSGRP = ["global1","global2"]} ) )


    i wanna pick out values in {tag} and {admins} and group/sort my hash with them. so all in all. I wanna 1. sort by key alphabetically1 after that, 2. sort by value in {tag} (so it groups all the 1s together all the 87s together etc), 3. drop all the ..{tag}==53 to the bottom. and finally 4. do that pattern match mentioned above and further group my records with that.

    foreach my $server ( sort {$my_server_hash {$a} cmp $my_server_hash +{$b} && $my_server_hash{$a}{tag} <=> $my_server_hash{$b} +{tag} } keys %my_server_hash) { my $member = $my_server_hash{$server}{ADMINS}; $servercount++; $access = $my_server_hash{$server}{tag}; if ($access == 1) { $comment = ""; $color="#99FF33"; } elsif ($member =~ s/$account/FOUND:$account/i && $acces +s !=1) { # this means password is wrong! $color = "#FF3366"; $comment = "<a name=\"password_wrong\"><b>$ +account password is wrong! </b></a>"; } elsif ($access == 53) { $comment = " <a name=\"unavailable\"> <font color + = \"white\"> <b>machine unavailable! <br></b></a> "; $color = "#996666"; } elsif($my_server_hash{$server}{ADMINS}) { $comment = " <a name=\"no_account\"><b> $ac +count account does not exist</b> </a>"; $color = "#FF3333"; } else { $comment = " <a name=\"unknown\"> <font co +lor = \"white\"> <b>unable to access! <br></b></a> "; $color = "#FF66CC"; } server_data_row("19%",$color, "27%", "Verdana, Arial, Helvetica, sa +ns-serif","4",$server,$htm_pass_handle); server_data_row("12%",$color, "27%", "Courier New, Courier, mono"," +2","$member",$htm_pass_handle); server_data_row("69%",$color, "27%", "Courier New, Courier, mono"," +3",$access."<b> $comment</b>",$htm_pass_handle,"</tr>"); } # foreach server


    I think i have enough to go on i will probably go down the graff has suggested although i dont think i'm understanding the concept to implement it properly.

    any further nudges in the right direction are very welcome.

    for now back to my code. thanks again. C.

      For the sort of sorting (um, sorry) you seem to want to do, treat a {tag} value of 53 as an arbitrary 'high' value and anything else as an arbitrary 'low' value (i.e., just have two) for one level of sorting, and then append to that the sorting you're already doing. To wit:

      sub server_sort { # bi-valued key = 0 if {tag} is not 53 and 1 if {tag} is 53 (($my_server_hash{$a}{tag} == 53) <=> ($my_server_hash{$b}{tag} == 53)) || $a cmp $b || $my_server_hash{$a}{tag} <=> $my_server_hash{$b}{tag} } my @server_names = sort &server_sort keys %my_server_hash; # now the server names are sorted with the 53 tags grouped # separately from the rest.

      Of course, with a large number of items, this manner of sorting is beau coup inefficient; you may want to precalculate the keys, a la the Schwartzian Transform (or dare I suggest the Advanced Sorting - GRT - Guttman Rosler Transform?).

      In this case, the precalculated keys might consist of the various components appended together:

      Update: Admittedly, pack would be far more efficient than sprintf in the following, but I wanted to illustrate the point without obfuscating it any more than necessary.

      sub make_key { my $sn = shift; my $tag = $my_server_hash{$sn}{tag}; # NOTE: presumes largest server name may be contained # in 20 chars and that {tag} values won't exceed 99,999 return sprintf "%1d%20s%5d", ($tag == 53), $sn, $tag}; } sub decode_key { my $key = shift; return substr $key, 1, 20; } my @server_names = map { decode_key($_) } sort { $a cmp $b } map { make_key($_) } keys %my_server_hash;

      Similarly, your other criteria (looks like {tag} is contained within the {ADMINS} key, whatever that means) might be incorporated by changing the bi-valued key to a tri-valued key (0, 1, 2) and inserting that criteria between the two existing ones.

      sub make_key { my $sn = shift; my $tag = $my_server_hash{$sn}{tag}; my $member = $my_server_hash{$sn}{ADMINS}; my $key = ($tag == 53) ? 2 : (($member =~ s/$tag/FOUND:$tag/i) && $tag != 1) ? 1 : 0; return sprintf "%1d%20s%5d", $key, $sn, $tag}; }

      Hope this helps.

      dmm

      If you GIVE a man a fish you feed him for a day
      But,
      TEACH him to fish and you feed him for a lifetime