Sort CSV based on a certain column?

前端 未结 7 923
自闭症患者
自闭症患者 2020-12-18 09:50

I\'m sure I\'ve done this in the past and there is something small I\'m forgetting, but how can I sort a CSV file on a certain column? I\'m interested in answers with and wi

相关标签:
7条回答
  • 2020-12-18 10:49

    As CSV is a pretty complex format, it is better to use a module that does the work for us.

    Following is an example using the Text::CSV module:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use constant AGE => 1;
    
    use Text::CSV;
    
    my $csv = Text::CSV->new();
    
    my @rows;
    while ( my $row_ref = $csv->getline( \*DATA ) ) {
        push @rows, $row_ref;
    }
    
    @rows = sort { $a->[AGE] <=> $b->[AGE] } @rows;
    
    for my $row_ref (@rows) {
        $csv->combine(@$row_ref);
        print $csv->string(), "\n";
    }
    
    __DATA__
    name,25,female
    name,24,male
    name,27,female
    name,21,male
    
    0 讨论(0)
提交回复
热议问题