KW.pm The Schwartzian Transform #7

Defining Sort Criteria

  • Can add an anonymous subroutine block to customize sort order

                @sorted_nums = sort { $a <=> $b } @nums
                # @nums has 1 .. 10;
  • Perl puts two of the values from the list into $a and $b

  • Block compares values and returns -1, 0 or 1

    • 0 means $a and $b are identical

    • -1 means $b comes first

    • 1 means $a comes first

  • <=> does this for numbers

  • cmp for strings

 

<< Previous | Index | Next >> Copyright © 2003 Daniel Allen