首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Perl按升序或降序排序单个列

使用Perl按升序或降序排序单个列
EN

Stack Overflow用户
提问于 2013-09-28 16:26:36
回答 1查看 1.2K关注 0票数 1

我试图使用Perl对文本文件中的下列价格列进行排序。

代码语言:javascript
运行
复制
Time    Num    Size     Price Act | Act Price   Size    Num       Time  
11:30:12.957    1   3000 11.90  A  |  A  11.05   500     1      11:30:12.954   
11:30:12.957    1   100  11.75  A  |  A  14.00   1676    3      11:30:12.957

我可以将文本文件读取到数组中,并按行对其进行排序,但我想不出如何按升序或降序排序特定的列?试着一次读取文本文件中的一个元素,如下所示,然后尝试按降序排序第一个Price

代码语言:javascript
运行
复制
use strict;
use warnings;

open(my $file_handle, '<', 'Data.txt') or die("Error: File cannot be opend:  $!");

my @words;

while (<$file_handle>) {
chomp;
@words = split(' ');
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-28 16:32:50

代码语言:javascript
运行
复制
use strict;
use warnings;

open(my $file_handle, '<', 'Data.txt') or die("Error: File cannot be opend:  $!");

my @rows;

while (<$file_handle>) {
  $. > 1 or next; # skip header line
  chomp;
  push @rows, [ split ]; # split current line on \s+ 
}

# sort descending on 4-th column
@rows = sort { $b->[3] <=> $a->[3] } @rows;

# ascending sort on same column
# @rows = sort { $a->[3] <=> $b->[3] } @rows;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19069071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档