在perl中对数组进行排序

时间:2013-10-25 10:02:16

标签: perl sorting

我有一个带元素的数组

@a =(mem_64x128,mem_8x64,mem_8x128,mem_128x64);

我希望以下列方式对数组进行排序

   mem_8x64,mem_8x128,mem_64x128,mem_128x64

但是当我sort @a时,我得到的输出是

mem_128x64
mem_64x128
mem_8x64
mem_8x128

任何人都可以帮忙。谢谢

5 个答案:

答案 0 :(得分:4)

使用自定义比较功能sort (perldoc)

sort {
   my ($c,$d) = $a =~ /(\d+)x(\d+)/;
   my ($e,$f) = $b =~ /(\d+)x(\d+)/;
   $c<=>$e || $d<=>$f;
} @a;

或更快的一个:

my %h;
@a = sort  {
   $h{$a} || ( @{$h{$a}} = $a =~ /(\d+)x(\d+)/ );
   $h{$b} || ( @{$h{$b}} = $b =~ /(\d+)x(\d+)/ );
   $h{$a}->[0] <=> $h{$b}->[0] || $h{$a}->[1] <=> $h{$b}->[1];
} @a;

答案 1 :(得分:3)

尝试这样的事情:

#!/usr/bin/perl
use strict;
use warnings;

my @a =("mem_64x128","mem_8x64","mem_8x128","mem_128x64");

print sort byFirst sort bySecond @a;

sub byFirst{
# Extract first number from a
my $y=$a;
$y =~ s/.*_//;
$y =~ s/x.*//;

# Extract first number from b
my $z=$b;
$z =~ s/.*_//;
$z =~ s/x.*//;
return $y <=> $z;
}

sub bySecond{
# Extract second number from a
my $y=$a;
$y =~ s/.*x//;

# Extract second number from b
my $z=$b;
$z =~ s/.*x//;
return $y <=> $z;
}

答案 2 :(得分:2)

这是一种方法。

use warnings;
use strict;


my @a = ('mem_64x128', 'mem_8x64', 'mem_8x128', 'mem_128x64');

my @sorted_a = sort { (split /[_x]/, $a)[1] <=> (split /[_x]/, $b)[1]
                           or
          (split /[_x]/, $a)[2] <=> (split /[_x]/, $b)[2]
} @a;

print "$_\n" foreach @sorted_a;

<强>输出

mem_8x64
mem_8x128
mem_64x128
mem_128x64

答案 3 :(得分:2)

这是另一个用例,CPAN模块nsort中的Sort::Naturally函数可以像人们期望的那样工作:

@a =(mem_64x128,mem_8x64,mem_8x128,mem_128x64); # no strict!
use Sort::Naturally qw(nsort);
print join(',', nsort @a), "\n";

输出是:

mem_8x64,mem_8x128,mem_64x128,mem_128x64

答案 4 :(得分:1)

元素按第一个和第二个数字按升序排序,

my @r = qw(mem_64x128 mem_8x64 mem_8x128 mem_128x64);

@r = map { $_->[0] }
  sort {
    $a->[1] <=> $b->[1] || $a->[2] <=> $b->[2]
  }
  map { [$_, /(\d+)/g ] } @r;

print "@r\n";

输出

mem_8x64 mem_8x128 mem_64x128 mem_128x64