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

Hi, i'm new to perl and was hoping i could get some help here....... i'm currently running a foreach loop that looks like this:
foreach $name (sort keys by %x) { $a= $x{$name} ; $b= $y{$name} ; $total = $a/$b; print $name, $a, $b, $total }
and i print the output into a file which looks like this:
$name $a $b $total abc 2 3 5 xyz 2 4 6
right now i have my output sorted by x, but i want a descending sort using the values from total....how would i implement this by still using the foreach loop i have and getting the values printed out as before only sorted by descending values of total? thanks.

Update: Added <code> tags. larsen

Replies are listed 'Best First'.
Re: help with sort by value
by DamnDirtyApe (Curate) on Jul 18, 2002 at 23:53 UTC

    Since you can't know how to sort the totals until they have all been calculated, I think it would be a good idea for you to build an intermediate data structure (an array of hashes would be ideal) containing the name, the two associated values, and the total. Either that, or rearrange your input data into something a little better organized, ie. one set of names that points at both values. Rather than:

    %x = ( 'abc' => 2 ) ; %y = ( 'abc' => 3 ) ;

    Try something like:

    @data = ( { 'name' => 'abc', 'x' => 2, 'y' => 3 }, { 'name' => 'xyz', 'x' => 4, 'y' => 5 } ) ;

    I realize this may not be so simple if your data is coming from somewhere else, but keep it in mind nonetheless.

    i'm currently running a foreach loop that looks like this:

    Er, the one you posted doesn't run. AFAIK, sort keys by %x isn't Perl. Also, your sample data doesn't match your code. I think you'll get better help if you post:

    • Your input data;
    • Your actual foreach loop;
    • Your actual output; and
    • Your desired output.

    _______________
    D a m n D i r t y A p e
    Home Node | Email
      That won't work because I need to do the computation within the foreach loop based on previous code.....Is there anyway I can use sort() with the print() statement?

        How can you sort something you haven't had the opportunity to calculate yet? And, why is this important? Like I said, please post some code.


        _______________
        D a m n D i r t y A p e
        Home Node | Email
Re: help with sort by value
by Russ (Deacon) on Jul 18, 2002 at 22:59 UTC
    Have you checked Categorized Q&A?

    We keep lots of great information there. ;-)

    Russ
    Brainbench 'Most Valuable Professional' for Perl