我正在尝试对perl中的数组数据结构中存在的键值对进行排序。但是,当有多个条目时,我无法解析如何排序。
以下是我的代码:
my @users = (
{id => 1, name => "Frank"},
{id => 10, name => "Joe"},
{id => 5, name => "Paul"}
);
我希望输出按ID升序排序:
{id => 1, name => "Frank"},
{id => 5, name => "Paul"},
{id => 10, name => "Joe"}
以下是我的努力:
use strict;
use warnings;
use 5.010;
my @users =
(
{id => 1, name => "Frank"},
{id => 10, name => "Joe"},
{id => 5, name => "Paul"}
);
foreach my $name (keys %users) {
printf "%-8s %s\n",$users{id},$users{name};
}
任何建议都会非常有用。
答案 0 :(得分:5)
You have conflicting specifications of your data, but does this do what you need?
use strict;
use warnings;
use 5.010;
my @users = (
{ id => 1, name => "Frank" },
{ id => 10, name => "Joe" },
{ id => 5, name => "Paul" },
);
for my $item ( sort { $a->{id} <=> $b->{id} } @users ) {
printf "%-8s %s\n", $item->{id}, $item->{name};
}
1 Frank
5 Paul
10 Joe
答案 1 :(得分:2)
You seem to have an incorrect understanding of Perl Hashes.
Also use sort
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
my %users =
(
1 => {id => 1, name => 'Frank'},
2 => {id => 10, name => 'Joe' },
3 => {id => 5, name => 'Paul' }
);
foreach my $serial (sort {$users{$a}{id} <=> $users{$b}{id}} keys %users)
{
printf "%-8s %s\n",$users{$serial}{id},$users{$serial}{name};
}
答案 2 :(得分:0)
Here's a version using sort:
#! /usr/bin/perl
use strict;
use warnings;
use 5.010;
my @users =
(
{ id => 1 , name => "Frank" },
{ id => 10, name => "Joe" },
{ id => 5 , name => "Paul" }
);
@users = sort { $a->{id} <=> $b->{id} } @users;
foreach my $user ( @users ) {
printf "%-8s %s\n" , $user->{id}, $user->{name};
}
[edit] changed to sort by ID
答案 3 :(得分:0)
最简单的方法是使用List::UtilsBy
中的nsort_by
功能:
List :: UtilsBy:https://metacpan.org/pod/List::UtilsBy
use List::UtilsBy qw( nsort_by );
my @users = (
{id => 1, name => "Frank"},
{id => 10, name => "Joe"},
{id => 5, name => "Paul"}
);
foreach my $user ( nsort_by { $_->{id} } @users ) {
printf "%-8s %s\n" , $user->{id}, $user->{name};
}