First ... Back ... Next ... Last ... (Notes home)

Sorting with sort

Perl includes a powerful sort function that can operate in a variety of ways, always in the LIST context. It's easy, but remember that sorting is still relatively computationally expensive. Use it when you need it.

  • Add reverse prior to sort to reverse the order of the sort.
  • Many sort examples from man perlfunc
    # sort lexically
    @articles = sort @files;
    
    # same thing, but with explicit sort routine
    @articles = sort {$a cmp $b} @files;
    
    # now case-insensitively
    @articles = sort {uc($a) cmp uc($b)} @files;
    
    # same thing in reversed order
    @articles = sort {$b cmp $a} @files;
    
    # sort numerically ascending
    @articles = sort {$a <=> $b} @files;
    
    # sort numerically descending
    @articles = sort {$b <=> $a} @files;
    
    # this sorts the %age hash by value instead of key
    # using an in-line function
    @eldest = sort { $age{$b} <=> $age{$a} } keys %age;
    
    # sort using explicit subroutine name
    sub byage {
        $age{$a} <=> $age{$b};  # presuming numeric
    }
    @sortedclass = sort byage @class;
    
    sub backwards { $b cmp $a }
    @harry  = qw(dog cat x Cain Abel);
    @george = qw(gone chased yz Punished Axed);
    print sort @harry;
            # prints AbelCaincatdogx
    print sort backwards @harry;
            # prints xdogcatCainAbel
    print sort @george, 'to', @harry;
            # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
    

    First ... Back ... Next ... Last ... (Notes home)

    UAF Computer Science
    Prof. Greg Newby