Search code examples
perlsortingperl-data-structures

sort by two columns using sort and map in Perl


I have the list as

@emprecords = (
                  ['pavan',24,25000],
                  ['kumar',25,35000],
                  ['ajay',22,35000],
                  ['vijay',25,20000]
);

i need to sort them by lowest age first with highest slary first .


Solution

  • Use <=> for a numeric comparison and a conditional or to check the salary when age is equal:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use Data::Dumper;
    
    my @emprecords = sort {
                    $a->[1] <=> $b->[1]
                            or
                    $b->[2] <=> $a->[2]
                    }
                    (  ['pavan',24,25000],
                      ['kumar',25,35000],
                      ['ajay',22,35000],
                      ['vijay',25,20000]
    );
    
    print Dumper \@emprecords;
    

    Run it like:

    perl script.pl
    

    That yields:

    $VAR1 = [
              [
                'ajay',
                22,
                35000
              ],
              [
                'pavan',
                24,
                25000
              ],
              [
                'kumar',
                25,
                35000
              ],
              [
                'vijay',
                25,
                20000
              ]
            ];