【问题标题】:How does one print the elements of a hash in the order they were added to the hash如何按照添加到散列的顺序打印散列的元素
【发布时间】:2013-11-08 22:36:26
【问题描述】:

如何按照添加到哈希中的顺序打印哈希的键/值对。

例如:

%hash = ("a", "1", "b", "2", "c", "3");
while (($key, $value) = each %hash) {
   print "$key", "$value\n";
}

以上结果如下:

c3
a1
b2

我正在寻找一种打印以下内容的方法:

a1
b2
c3

提前致谢!

【问题讨论】:

    标签: perl hash


    【解决方案1】:

    如何按照它们在哈希中出现的顺序打印哈希的键/值对。

    您使用的代码正是这样做的。 c3,a1,b2是当时hash中元素出现的顺序。

    您实际上想要按照插入的顺序打印它们。为此,您需要跟踪元素的插入顺序,或者您必须使用哈希以外的其他内容,例如上述Tie::IxHashTie::Hash::Indexed

    【讨论】:

    • 现在首选哪个?
    • @mpapec,我从来都不需要。我总是能够使用数组或数组+哈希组合来完成。
    【解决方案2】:

    哈希没有排序。您需要选择其他数据结构。

    【讨论】:

    • 不知道这个,谢谢。然后必须找到解决方法:)
    【解决方案3】:

    您需要Tie::IxHash 模块来获取有序哈希,

    use Tie::IxHash;
    
    tie(my %hash, 'Tie::IxHash');
    %hash = ("a", "1", "b", "2", "c", "3");
    
    while (my ($key, $value) = each %hash) {
      print "$key", "$value\n";
    }
    

    【讨论】:

      【解决方案4】:

      散列通常是无序的。您可以改为使用有序哈希。从 CPAN 尝试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'
      

      【讨论】:

      • 这确实有效,但是,我试图不包含模块。将不得不找到另一种方法来解决这个问题。不过感谢您的帮助:)
      【解决方案5】:

      因为您不想使用任何提到的模块(Tie::IxHash 和 Tie::Hash::Indexed),并且因为哈希是 unordered collections(如前所述) ,您必须在插入值时存储此信息:

      #!/usr/bin/perl
      use warnings;
      use strict;
      
      my %hash;
      my %index; #keep track of the insertion order
      my $i=0;
      for (["a","1"], ["b","2"], ["c","3"]) { #caveat: you can't insert values in your hash as you did before in one line
          $index{$_->[0]}=$i++;
          $hash{$_->[0]}=$_->[1];
      }
      
      for (sort {$index{$a}<=>$index{$b}} keys %hash) {  #caveat: you can't use while anymore since you need to sort
         print "$_$hash{$_}\n";
      }
      

      这将打印:

      a1
      b2
      c3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-13
        • 2017-08-22
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        • 2013-08-10
        • 2013-11-24
        相关资源
        最近更新 更多