自定义数组排序在Perl [英] Custom array sort in perl

查看:89
本文介绍了自定义数组排序在Perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的待办任务一个Perl的数组,看起来像这样:

I have a perl array of to-do tasks that looks like this:

@todos = (
  "1 (A) Complete online final @evm4700 t:2010-06-02",
  "3 Write thank-you t:2010-06-10",
  "4 (B) Clean t:2010-05-30",
  "5 Donate to LSF t:2010-06-02",
  "6 (A) t:2010-05-30 Pick up dry cleaning",
  "2 (C) Call Chris Johnson t:2010-06-01"
);

这是第一个数字是任务的ID。如果一个任务有([A-Z])旁边,定义任务的优先级。我想要做的排序是在第一个地方优先项目的方式的任务阵列(并按照优先级从高到低,从A顺序 - Z):

That first number is the task's ID. If a task has ([A-Z]) next to, that defines the task's priority. What I want to do is sort the tasks array in a way that places the prioritized items first (and in order of descending priority, from A - Z):

@todos = (
  "1 (A) Complete online final @evm4700 t:2010-06-02",
  "6 (A) t:2010-05-30 Pick up dry cleaning",
  "4 (B) Clean t:2010-05-30",
  "2 (C) Call Chris Johnson t:2010-06-01"
  "3 Write thank-you t:2010-06-10",
  "5 Donate to LSF t:2010-06-02",
);

我不能使用普通的排序(),因为这些ID旁的任务,所以我假设需要某种定制的排序子程序的。但是,我如何在Perl中有效地完成这方面的知识是最小的。

I cannot use a regular sort() because of those IDs next to the tasks, so I'm assuming that some sort of customized sorting subroutine is needed. However, my knowledge of how to do this efficiently in perl is minimal.

感谢所有。

推荐答案

听起来像是你想要的的Schwartzian变换

@todos =
    map  { $_->[0] }
    sort { $a->[1] cmp $b->[1] or $a->[0] cmp $b->[0] }
    map  { [ $_, /^\d+ \(([[:alpha:]])\)/ ? $1 : "[" ] }
    @todos;

[是Z之后的字符;给这个优先来,否则unprioritized项目将优先项目后,对它们进行排序。

"[" is the character after "Z"; giving this "priority" to otherwise unprioritized items will sort them after the prioritized items.

可替换地,也许更容易抓握

Alternately, and perhaps more easily graspable:

@todos =
    map { substr $_, 1 }
    sort
    map { (/^\d+ \(([[:alpha:]])\)/ ? $1 : "[") . $_ }
    @todos;

这篇关于自定义数组排序在Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆