使用perl对包含字母数字的哈希值中的键进行排序

时间:2017-05-16 10:55:15

标签: perl hash

如何从哈希中对键进行排序(在键中,哈希中包含alphaNumeric),将哈希打印为输出

 %bibIdstr = (
      'bib16' => 'newbib12',
      'bib7' => 'newbib6',
      'bib11' => 'newbib9',
      'bib4' => 'newbib4',
      'bib2' => 'newbib2',
      'bib1' => 'newbib1',
      'bib18' => 'newbib13',
      'bib13' => 'newbib10',
      'bib14' => 'newbib11',
      'bib10' => 'newbib8',
      'bib8' => 'newbib7',
      'bib6' => 'newbib5',
      'bib3' => 'newbib3'
    );

我的代码:

foreach my $keys (sort (keys %bibIdstr))
{
    print $keys ."->". $bibIdstr{$keys} . "\n";
}

其打印输出

bib1->newbib1
bib10->newbib8
bib11->newbib9
bib13->newbib10
bib14->newbib11
bib16->newbib12
bib18->newbib13
bib2->newbib2
bib3->newbib3
bib4->newbib4
bib6->newbib5
bib7->newbib6
bib8->newbib7

但我的预期输出是:

bib1->newbib1
bib2->newbib2
bib3->newbib3
bib4->newbib4
bib6->newbib5
bib7->newbib6
bib8->newbib7
bib10->newbib8
bib11->newbib9
bib13->newbib10
bib14->newbib11
bib16->newbib12
bib18->newbib13

如果有人可以提供帮助,我们将不胜感激。

由于

1 个答案:

答案 0 :(得分:0)

试试这个:

%bibIdstr = (
      'bib16' => 'newbib12',
      'bib7' => 'newbib6',
      'bib11' => 'newbib9',
      'bib4' => 'newbib4',
      'bib2' => 'newbib2',
      'bib1' => 'newbib1',
      'bib18' => 'newbib13',
      'bib13' => 'newbib10',
      'bib14' => 'newbib11',
      'bib10' => 'newbib8',
      'bib8' => 'newbib7',
      'bib6' => 'newbib5',
      'bib3' => 'newbib3'
    );

sub sortByNumber($$){
my      $a = shift;
my      $b = shift;
        $a =~ s/bib//;
        $b =~ s/bib//;

        return $a <=> $b;
}

foreach my $keys (sort {sortByNumber($a,$b) }(keys %bibIdstr))
{
    print $keys ."->". $bibIdstr{$keys} . "\n";
}

输出:

bib1->newbib1
bib2->newbib2
bib3->newbib3
bib4->newbib4
bib6->newbib5
bib7->newbib6
bib8->newbib7
bib10->newbib8
bib11->newbib9
bib13->newbib10
bib14->newbib11
bib16->newbib12
bib18->newbib13