in reply to Re: Re: sort array by value in it
in thread sort array by value in it

Anonymous Monk,
Did you try the program? All you would have to do is swap $a and $b. I do not remember you saying you wanted it in descending order.

Cheers - L~R

Replies are listed 'Best First'.
Re: Re: Re: Re: sort array by value in it
by Anonymous Monk on May 04, 2004 at 16:33 UTC
    i didnt understand what the
    while <DATA>
    part was at...
    i just didnt understand to put it in the loop where i splitting lines or after it..
      Anonymous Monk,
      I do not have the real data that you have, so I improvised using the small snippet you provided. You also have not done an adequete job explaining your problem. I am going to do something Abigail would frown on and guess.
      • You have a list of hosts that you are processing
      • Each host involves a system command to see free disk space
      • The string with imbedded newlines containing the output is stored in a hash where the key is the host
      • When displaying the hosts disk free, you want the string sorted by a substring.
      If that is an accurate guess, you would modify my original code to look something like the following:
      for my $host ( keys %space ) { my @data; for ( split /\n/ , $space{$host} ) { next if /^host:volume/; my @field = $_ =~ /^([^:]+):([^\s]+)\s+(\d+)\s+(\d+)/; push @data, \@field; } for ( sort { $data[$a]->[2] <=> $data[$b]->[2] } 0 .. $#data ) { print join "\t" , @{ $data[$_] }; print "\n"; } }
      Now we are not mind readers and we do not have crystal balls. You are going to need to apply these techniques to your own code and modify accordingly. It would be nearly impossible to give you full blown working code with what little you have provided.

      Cheers - L~R

        Hi L~R. Im just curious about one part of your solution:

        for ( sort { $data[$a]->[2] <=> $data[$b]->[2] } 0 .. $#data ) { print join "\t" , @{ $data[$_] }; print "\n"; }

        Why did you code it this way I wonder? It seems odd that you are actually sorting a list of indexes and not the elements themselves. Theres no speed gain, in fact theres a loss in that each element requires two levels of dereferencing, and you have the added memory hit of constructing a list of indexes. Im really curious if there was any reason why you didnt just say

        print join("\t",@$_),"\n" for sort { $a->[2] <=> $b->[2] } @data;

        or possibly:

        print join "\n",map { join "\t",@$_ } sort { $a->[2] <=>$b->[2] } @dat +a;

        ---
        demerphq

          First they ignore you, then they laugh at you, then they fight you, then you win.
          -- Gandhi