如何打印散列元素的键/值对按照散列元素的添加顺序排列。如何按散列元素的顺序添加散列元素
例如:
%hash = ("a", "1", "b", "2", "c", "3");
while (($key, $value) = each %hash) {
print "$key", "$value\n";
}
以上结果如下:
c3
a1
b2
我正在寻找一种方式来打印如下:提前
a1
b2
c3
谢谢!
如何打印散列元素的键/值对按照散列元素的添加顺序排列。如何按散列元素的顺序添加散列元素
例如:
%hash = ("a", "1", "b", "2", "c", "3");
while (($key, $value) = each %hash) {
print "$key", "$value\n";
}
以上结果如下:
c3
a1
b2
我正在寻找一种方式来打印如下:提前
a1
b2
c3
谢谢!
既然你不想使用所提到的任何模块(领带:: IxHash和Tie ::哈希索引::),自此散列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
散列没有排序。您需要选择另一个数据结构。
你需要有序哈希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";
}
散列一般是无序的。您可以改为使用有序散列。尝试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'
这确实工作,但是,我试图不包括模块。 必须找到另一种方式来解决这个问题。 感谢您的帮助,虽然:) –
你怎么打印一个哈希的键/值对,在它们出现在哈希的顺序。
您使用的代码确实如此。 c3,a1,b2是当时元素出现在hash中的顺序。
你实际上想要按照它们插入的顺序打印它们。为此,您需要跟踪插入元素的顺序,否则您将不得不使用哈希以外的内容,例如前面提到的Tie::IxHash和Tie::Hash::Indexed。
这是现在的首选? –
@mpapec,我从来没有需要。我总是能够使用数组或数组+哈希组合。 – ikegami
不知道这一点,谢谢。将不得不找到一个解决方法然后:) –