3

我想一一遍历HASH。不是随机方式。任何的想法。例如我有这样的哈希文件......

our %HASH = (
'rajesh:1700'  =>  Bangalore,
'rajesh:1730'  =>  Delhi,
'rajesh:1770'  =>  Ranchi,
'rajesh:1780'  =>  Mumbai,
'rajesh:1800'  =>  MYCITY,
'rajesh:1810'  =>  XCF,
);

它应该以相同的方式打印。我尝试了以下但失败了。有任何想法吗?

while ( my $gPort = each %HASH)
{
    print "$gPort\n";
}


for my  $gPort ( keys %HASH )
{
    print "$gPort\n";
}
4

4 回答 4

4

给定您问题中的键,对排序比较器进行简单更改即可获得所需的输出。

for my $gPort (sort keys %HASH) {
  print "$gPort => $HASH{$gPort}\n";
}

注意:上面的代码假设键中的所有数字都出现在相同的位置并具有相同的长度。例如,一个rajesh:001775键将首先出现,而不是在 1770 和 1780 之间。

于 2012-04-05T12:26:50.133 回答
1

您可以按 VALUE(不是键)排序并打印出哈希值。

for my $gPort (sort { $HASH{$a} <=> $HASH{$b} } keys %HASH) {
  print "$gPort => $HASH{$gPort}\n";
}
于 2012-04-05T12:55:38.923 回答
0

看看Data::Dumper。特别是,如果您设置$Data::Dumper::Sortkeys,那么您将按排序顺序获得转储。

举个例子:

use Data::Dumper;
$Data::Dumper::Sortkeys = 1;

my %some_hash;

# code to populate hash
[ . . . ]

print Dumper(\%some_hash);

当然,这仅在您想清楚地转储哈希时才有效。如果您希望以其他格式完成打印,则只需对键进行排序并打印,例如

foreach my $key (sort keys %some_hash) {
    print "[KEY]: $key; [VAL]: $some_hash{$key}\n";
}
于 2012-04-05T13:26:18.273 回答
0

如果您希望在哈希中保留元素的插入顺序,那么Tie::IxHash可能是适合您的工具。它的用法很简单:

向您展示简单的示例:

    use Tie::IxHash;        
    tie my %days_in => 'Tie::IxHash',
            January   => 31,
            February  => 28,
            March     => 31,
            April     => 30,
            May       => 31,
            June      => 30,
            July      => 31,
            August    => 31,
            September => 30,
            October   => 31,
            November  => 30,
            December  => 31;       


      print join(" ", keys %days_in), "\n";        
    # prints: January February March April May June July August
    # September October November December
于 2012-04-05T13:43:56.237 回答