SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Feb 2010
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Perl Sort Array of Arrays

    Hello,

    I have an Array of Arrays.

    I need to sort the entire array on the 12 field in each array. The field is a datefield, so newer date at the top and older date at the bottom.

    I tried the normal sort functions and I cannot figure it out. Any help or pointing to docs on the web is much appreciated.

    Thanks!

    Jim

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,578
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Write your own sort function that uses the '12 field' in the comparison

    http://en.wikipedia.org/wiki/Quicksort#Algorithm

  3. #3
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,283
    Mentioned
    51 Post(s)
    Tagged
    2 Thread(s)
    Code:
    @AoA = sort { $a->[12] > $b->[12] } @AoA
    An example sort function using the contents of the 12th (13th) item... but you didn't say what your date format was. Use a CPAN Date module.

    http://www.perlmonks.org/?node_id=667645

    General docs are at perldoc.perl.org.

    PS hubby wrote this, I'm not awesome enough to write my own sort functions in Perl : )

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    use strict;
    use warnings;
    use 5.010;
    
    
    my @AoA = (
        ['a', '2003-11-09', 'b'],
        ['c', '2003-11-01', 'd'],
        ['e', '2002-11-01', 'f'],
        ['g', '2003-10-01', 'h'],
        ['g', '2002-10-01', 'h'],
    );
    
    my @new_arr = sort {$a->[1] cmp $b->[1]} @AoA;
    
    for (@new_arr) {
        say "@$_";
    }
    
    --output:--
    g 2002-10-01 h
    e 2002-11-01 f
    g 2003-10-01 h
    c 2003-11-01 d
    a 2003-11-09 b


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •