#! \user/bin/perl
use strict;
#------------------------
#hash unwinding
#------------------------
my %tmp1 = qw{
1 a
2 b
3 c
4 d
5 e
};
my @tmp2 = %tmp1;
print "@tmp2\n";
#------------------------
#hash restore
#------------------------
my %tmp4;
my @tmp3 = qw(a b c d e);
my $n = 0;
foreach my $one (@tmp3){
$n = $n + 1;
$tmp4{$n} = "$one";
}
while( (my $key , my $value) == each %tmp4){
print "$key $value\n";
}
数组@tmp2由 哈希tmp1松绑而来,打印结果:4 d 1 a 3 c 2 b 5 e。
通过foreach循环,可还原哈希的键值对,再通过while循环打印出来,打印结果:
4 d
1 a
3 c
2 b
5 e
由于哈希内部存储是随机的,所有打印结果是一个乱序,若想按照一定顺序排列可通过sort进行排序。