【问题标题】:Sorting a hash from the first key to the last (Perl)从第一个键到最后一个键对哈希进行排序(Perl)
【发布时间】:2012-10-28 04:28:22
【问题描述】:

我有以下哈希,我希望按照我设置的顺序保留它;这甚至可能吗?如果没有,是否有替代方案?

my %hash = ('Key1' => 'Value1', 'Key2' => 'Value2', 'Key3' => 'Value3');

我需要编写自定义排序子程序吗?我有哪些选择?

谢谢!

【问题讨论】:

  • 不,数组也不保留插入顺序。 $a[1]="a"; $a[0]="b"; print "@a\n"; 打印 b a。数组和哈希都按照它们在物理上找到的顺序返回元素。
  • 出于什么原因需要对关联数组(哈希)进行排序?

标签: perl sorting hash


【解决方案1】:

http://metacpan.org/pod/Tie::IxHash

use Tie::IxHash;
my %hash;
tie %hash,'Tie::IxHash';

此哈希将保持其顺序。

【讨论】:

  • 我希望有一些不需要外部库的东西,但是,无论如何这应该可以解决问题。已测试并正常工作,谢谢!
【解决方案2】:

Tie::Hash::Indexed。引用其概要:

use Tie::Hash::Indexed;

tie my %hash, 'Tie::Hash::Indexed';

%hash = ( I => 1, n => 2, d => 3, e => 4 );
$hash{x} = 5;

print keys %hash, "\n";    # prints 'Index'
print values %hash, "\n";  # prints '12345'

【讨论】:

    【解决方案3】:

    尝试这样做:

    print "$_=$hash{$_}\n" for sort keys %hash;
    

    如果您希望它按字母顺序排序。

    如果您需要保留原订单,请查看其他帖子。

    http://perldoc.perl.org/functions/sort.html

    【讨论】:

      【解决方案4】:

      一种可能性是像您有时对数组所做的那样:指定键。

       for (0..$#a) {  # Sorted array keys
           say $a[$_];
       }
      
       for (sort keys %h) {  # Sorted hash keys
           say $h{$_};
       }
      
       for (0, 1, 3) {  # Sorted array keys
           say $h{$_};
       }
      
       for (qw( Key1 Key2 Key3 )) {  # Sorted hash keys
           say $h{$_};
       }
      

      您还可以按如下方式获取有序值:

       my @values = @h{qw( Key1 Key2 Key3 )};
      

      【讨论】:

        【解决方案5】:

        这取决于您将如何访问数据。如果您只想存储它们并访问最后/第一个值,您可以随时将哈希放入数组中并使用 push() 和 pop()。

        #!/usr/bin/env perl
        
        use strict;
        use warnings;
        
        use v5.10;
        
        use Data::Dumper;
        
        my @hashes;
        
        foreach( 1..5 ){
            push @hashes, { "key $_" => "foo" };
        }
        
        
        say Dumper(\@hashes);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-22
          • 1970-01-01
          • 2021-10-22
          • 2015-03-12
          • 1970-01-01
          • 2019-03-17
          • 1970-01-01
          相关资源
          最近更新 更多