首页 > 解决方案 > 如何按给定顺序提取哈希键?

问题描述

我有下一个哈希:

%hash =  (
  name => {
     pos => 1
  },
  name_xxx => {
     pos => 2
  },
  name_yyy => {
     pos => 3
  },
)

并想构造下一个数组(键必须按 排序pos):

qw/ name name_xxx name_yyy /

我想我应该做施瓦茨变换

按给定顺序提取哈希键的最短和/或最快方法是什么?

标签: perldata-structures

解决方案


您拥有的不是哈希,而是哈希引用(缺少逗号)。要获取密钥,请使用密钥和取消引用:

#!/usr/bin/perl
use warnings;
use strict;

my $hash_ref = {
    name     => {pos => 1},
    name_xxx => {pos => 2},
    name_yyy => {pos => 3},
};

my @keys = sort { $hash_ref->{$a}{pos} <=> $hash_ref->{$b}{pos} }
           keys %$hash_ref;
print "@keys\n";

推荐阅读