"75.00", SUBKEY2 =>-6ren">
gpt4 book ai didi

perl - 然后按子键对键排序——如果子键 undef 设置为空字符串

转载 作者:行者123 更新时间:2023-12-02 07:13:37 24 4
gpt4 key购买 nike

my %data (
KEY1 => {
SUBKEY1 => "Canada",
SUBKEY3 => "75.00",
SUBKEY2 => "50.00",
},
KEY3 => {
SUBKEY2 => "150.00",
},
KEY2 => {
SUBKEY3 => "200.00",
SUBKEY1 => "Mexico",
},
);

如何打印按键名排序并按子键名排序的每个键名的列表?

这是我要打印的内容:(请注意,如果未定义子项,则会出现一个带有空字符串的子项的占位符)

KEY1: SUBKEY1 is "Canada"
KEY1: SUBKEY2 is "50.00"
KEY1: SUBKEY3 is "75.00"
KEY2: SUBKEY1 is ''
KEY2: SUBKEY2 is "150.00"
KEY2: SUBKEY3 is ''
KEY3: SUBKEY1 is "Mexico"
KEY3: SUBKEY2 is ''
KEY3: SUBKEY3 is "200.00"

最佳答案

use strict;
use warnings;

my %data = (
KEY1 => {
SUBKEY1 => "Canada",
SUBKEY3 => "75.00",
SUBKEY2 => "50.00",
},
KEY3 => {
SUBKEY2 => "150.00",
},
KEY2 => {
SUBKEY3 => "200.00",
SUBKEY1 => "Mexico",
},
);

my %all_sub_keys;
for my $sub_hash (values %data){
$all_sub_keys{$_} ++ for keys %$sub_hash;
}

my @all_sub_keys = sort keys %all_sub_keys;

for my $k ( sort keys %data ){
for my $sk (@all_sub_keys){
my $val = exists $data{$k}{$sk} ? $data{$k}{$sk} : '--';
print join(' ', $k, $sk, $val), "\n";
}
}

关于perl - 然后按子键对键排序——如果子键 undef 设置为空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3206938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com