perl - 如何按给定顺序提取哈希键?
问题描述
我有下一个哈希:
%hash = (
name => {
pos => 1
},
name_xxx => {
pos => 2
},
name_yyy => {
pos => 3
},
)
并想构造下一个数组(键必须按 排序pos
):
qw/ name name_xxx name_yyy /
我想我应该做施瓦茨变换
按给定顺序提取哈希键的最短和/或最快方法是什么?
解决方案
您拥有的不是哈希,而是哈希引用(缺少逗号)。要获取密钥,请使用密钥和取消引用:
#!/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";
推荐阅读
- http - Why does HTTP/1.1 recommend to be conservative with opening connections?
- azure - 如果 eth0 未在 Azure VM 上配置怎么办
- azure - Why does my Azure Function function key keep regenerating?
- ruby-on-rails - Rails is autoloading association from console
- javascript - Javascript警报功能不等待
- r - lapply 并应用于列表 R 的每个组件和元素
- selenium - Chrome Selenium IDE 3.4.5 extension "execute script" command not storing as variable
- ios - What is the equivalent of iOS layoutSubviews for UWP?
- javascript - 错误:未捕获(在承诺中)类型错误:_this2.next 不是 reactJS 中的函数
- ansible - How do I pass a dictionary to an ansible ad-hoc command?