Perl分类帮助



我正在尝试将泡泡排序实现到我的脚本中,以使我可以按字母顺序排列数据。

**NetworkManager** Nov  8 13:24:23 osboxes <info> disable requested (sleeping: no  enabled: yes) NetworkManager[1249]:
**dhclient** Nov  8 15:52:45 osboxes DHCPOFFER of 192.168.253.129 from 192.168.253.254 dhclient:
**dhclient** Nov  8 15:52:45 osboxes DHCPACK of 192.168.253.129 from 192.168.253.254 dhclient:
**dnsmasq** Nov 13 17:52:35 osboxes using nameserver 192.168.253.2#53 dnsmasq[1637]:

这就是文件的外观,因此请阅读文件,然后将其存储到数组中。

我希望能够用一开始(在** **)中对数据排序,以便输出看起来像:

**dhclient** Nov  8 15:52:45 osboxes DHCPOFFER of 192.168.253.129 from 192.168.253.254 dhclient:
**dhclient** Nov  8 15:52:45 osboxes DHCPACK of 192.168.253.129 from 192.168.253.254 dhclient:    
**dnsmasq** Nov 13 17:52:35 osboxes using nameserver 192.168.253.2#53 dnsmasq[1637]:
**NetworkManager** Nov  8 13:24:23 osboxes <info> disable requested (sleeping: no  enabled: yes) NetworkManager[1249]:

没有理由为此问题实现气泡排序(有没有吗?)。

my @new_array = sort @original_array;

使对案例不敏感的排序:

my @new_array = sort {lc($a) cmp lc($b)} @original_array; 

如果您必须使用气泡排序,这似乎是一个很好的参考,但是示例是用于数字数量而不是字符串。我会修改使用字符串比较操作员cmp,类似于上面的sort块。

sub bubble_sort {
    for my $i (0 .. $#_){
        for my $j ($i + 1 .. $#_){
            my ($a,$b) = @_[$i, $j];
            # cmp returns -1 if the lefthand side is "less than" the right
            if ((lc($a) cmp lc($b)) == 1) {
                @_[$i, $j] = @_[$j, $i];
            }
        }
    }
}
bubble_sort(@array);
print "$_n" for @array;

最好的方法是

LC_ALL=C sort -f

如果您坚持使用perl:

use autodie;
open my $fh, 'LC_ALL=C sort -f |';
print <$fh>;

哦,你是说在perl中对其进行排序:

use feature qw(fc);
print sort {fc $a cmp fc $b}, <>;

或更有效地用于更大的文件:

use feature qw(fc);
print map $_->[0], sort {$a->[1] cmp $b->[1]} map [$_, fc], <>;

并注意我不必使用**做任何事情,因为它们不会影响您的数据的输出顺序。

另外,请注意,我不使用lcuc,因为它不能正确地适用于所有语言,并且使用它们而不是fc是一个坏习惯。

最新更新