如何使用perl按值对哈希进行排序?
我有这个密码如何使用perl按值对哈希进行排序?,perl,sorting,hash,Perl,Sorting,Hash,我有这个密码 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){
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";
}
这表明:
丰田红本田黄福特蓝
需要帮忙按Make分类 plusplus是对的。。。hashref数组可能是更好的数据结构选择。它也更具可伸缩性;使用
按钮添加更多车辆
:
print "$_->{Make} $_->{Color}" for
sort {
$b->{Make} cmp $a->{Make}
} values %hash;
my @cars = (
{ make => 'Toyota', Color => 'Red' },
{ make => 'Ford' , Color => 'Blue' },
{ make => 'Honda' , Color => 'Yellow' },
);
foreach my $car ( sort { $a->{make} cmp $b->{make} } @cars ) {
foreach my $attribute ( keys %{ $car } ) {
print $attribute, ' : ', $car->{$attribute}, "\n";
}
}
如果您的散列键是数字的,那么hashref数组是否更适合保存数据?(可能不是,但值得考虑)随机观察:应该避免使用
$a
和$b
,因为它们与现有全局变量冲突。
my @cars = (
{ make => 'Toyota', Color => 'Red' },
{ make => 'Ford' , Color => 'Blue' },
{ make => 'Honda' , Color => 'Yellow' },
);
foreach my $car ( sort { $a->{make} cmp $b->{make} } @cars ) {
foreach my $attribute ( keys %{ $car } ) {
print $attribute, ' : ', $car->{$attribute}, "\n";
}
}