gpt4 book ai didi

perl - 如何使用 perl 按值对散列的散列进行排序?

转载 作者:行者123 更新时间:2023-12-03 18:27:33 27 4
gpt4 key购买 nike

我有这个代码

use strict;
use warnings;

my %hash;
$hash{'1'}= {'Make' => 'Toyota','Color' => 'Red',};
$hash{'2'}= {'Make' => 'Ford','Color' => 'Blue',};
$hash{'3'}= {'Make' => 'Honda','Color' => 'Yellow',};

foreach my $key (keys %hash){
my $a = $hash{$key}{'Make'};
my $b = $hash{$key}{'Color'};
print "$a $b\n";
}

这个输出:

Toyota Red Honda Yellow Ford Blue



需要帮助按 Make 排序。

最佳答案

#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
1 => { Make => 'Toyota', Color => 'Red', },
2 => { Make => 'Ford', Color => 'Blue', },
3 => { Make => 'Honda', Color => 'Yellow', },
);

# if you still need the keys...
foreach my $key ( #
sort { $hash{$a}->{Make} cmp $hash{$b}->{Make} } #
keys %hash
)
{
my $value = $hash{$key};
printf( "%s %s\n", $value->{Make}, $value->{Color} );
}

# if you don't...
foreach my $value ( #
sort { $a->{Make} cmp $b->{Make} } #
values %hash
)
{
printf( "%s %s\n", $value->{Make}, $value->{Color} );
}

关于perl - 如何使用 perl 按值对散列的散列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4671960/

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