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

@allgsplane = sort { ($g2o{$a} cmp $g2o{$b}) || ($a <=> $b) } @allgs;
Can someone plz explain to me in English what this does? ....thanx a million...

I should perhaps note that the contents of @allgs is something like "32 61 33 34 35 37 37 38 39 40 46 58 43 41 56 53 59 51 45 47" ...thanx again...

Replies are listed 'Best First'.
Re: can someone plz decode this sort for me?
by Corion (Patriarch) on Aug 08, 2007 at 06:21 UTC

    The interesting part is the sort block. It consists of two expressions, $g2o{$a} cmp $g2o{$b} and $a <=> $b.

    The cmp operator returns three possible values, +1, 0 or -1, depending on whether the left side is greater, equal or smaller than the right side when compared as strings. The same holds true for the <=> ("spaceship") operator, except the comparison is done as numbers.

    So putting this together, the sort block first compares $g2o{$a} to $g2o{$b} as strings, and if the two are equal as strings it compares $a and $b as numbers to determine which comes first.

    Basically the sort block seems to sort first on the values of %g2o and then on the numerical value of @allgs.

    PS: Plz right n full English wrds - it maeks it easier 4 us 2 hlp u. Txtspk might be OK for your mobile but not here.

      Ah...thank you bart & Corion for the clarification. Now I know what it's really doing.

      --Rob
Re: can someone plz decode this sort for me?
by bart (Canon) on Aug 08, 2007 at 06:20 UTC
    The items from @allgs (which would appear to be numbers) will be sorted according to their associated value in the hash %g2o (compared as string), or, if equal, the smallest value (as a number) comes first.

    For example:

    %g2o = ( 128 => 'a', 13 => 'b', 34 => 'a', 28 => 'c' ); @allgs = (128, 13, 34 ); @allgsplane = sort { ($g2o{$a} cmp $g2o{$b}) || ($a <=> $b) } @allgs; print "@allgsplane\n";
    prints
    34 128 13
    All items with the value 'a' in the hash (34, 128) come before the item with value 'b' (13), because 'a' comes before 'b', but since there are two items with 'a', the smaller one (34) comes before the larger one (128).

    Note that my hash contains more items than the list I'm sorting, but those will simply be ignored.

    If the hash contains fewer items than the list, then it'll still work, with the missing items getting a default value of 0 (actually undef, but numerically, that is 0), but with "use of unitialized value" warnings.