我正在嘗試通過 location_id 對 Perl 中的以下資料結構進行排序。
my $employees = $dbh->selectall_arrayref(qq[
SELECT name, type, code, emp_cat_id,
percentage, location_id
FROM table_1
],{ Slice => {} });
for my $row (@$employees) {
push @{
$args->{employees}{ $row->{emp_cat_id} }
}, $row;
}
例子:
123 => [
{
percentage => 0.25,
code => "XYZ",
name => "John Doe",
type => "pt",
location_id => 001,
emp_cat_id => 123
}
],
555 => [
{
percentage => 0.50,
code => "ZZZ"
name => "Chris Cringle",
type => "ft",
location_id => 007,
emp_cat_id => 555
},
{
percentage => 0.25,
code => "XXX"
name => "Tom Thompson",
type => "pt",
location_id => 002,
emp_cat_id => 555
}
]
對于每個 emp_cat_id,我需要結構以 asc 順序包含 location_ids。
我已經嘗試了以下操作,但是我得到了“在第 # 行的無效背景關系中無用使用排序”或“在 # 行在標量背景關系中無用使用排序”錯誤。
$args->{employees} = sort {
$a->{location_id} <=> $b->{location_id}
} $args->{employees};
任何幫助理解排序表示贊賞!
uj5u.com熱心網友回復:
問題是您在emp_cat_idof和555of處對陣列(ref)123進行排序,因此需要取消參考以對這些陣列參考進行排序。所以
foreach my $id (keys $args->{employees}) {
@{ $args->{employees}{$id} } = sort {
$a->{location_id} <=> $b->{location_id}
}
@{ $args->{employees}{$id} }
}
(使用問題中顯示的結構進行測驗,此處省略)?
做這樣的事失去007進入7。這當然可以解決,如果這很重要,請告訴我。
如果您真的只有密鑰,請employees考慮提取$args->{employees}hashref 并使用它。會容易很多
use Storable qw(dclone);
my $employees = dclone $args->{employees}; # need deep copy
?哦,這就是整件事
use warnings;
use strict;
use feature 'say';
use Data::Dump qw(dd);
my $args = {
employees => {
123 => [
{
percentage => 0.25,
code => "XYZ",
name => "John Doe",
type => "pt",
location_id => 001,
emp_cat_id => 123
}
],
555 => [
{
percentage => 0.50,
code => "ZZZ",
name => "Chris Cringle",
type => "ft",
location_id => 007,
emp_cat_id => 555
},
{
percentage => 0.25,
code => "XXX",
name => "Tom Thompson",
type => "pt",
location_id => 002,
emp_cat_id => 555
}
]
}
};
foreach my $id (keys $args->{employees}) {
@{ $args->{employees}{$id} } = sort {
$a->{location_id} <=> $b->{location_id}
}
@{ $args->{employees}{$id} }
}
dd $args;
uj5u.com熱心網友回復:
那么,您有一個 hashref,其中每個元素都是一個 hashref 的 arrayref,應該根據 hashref 內部的鍵進行排序?
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my $hashref = {
123 => [
{
percentage => 0.25,
code => "XYZ",
name => "John Doe",
type => "pt",
location_id => 001,
emp_cat_id => 123
}
],
555 => [
{
percentage => 0.50,
code => "ZZZ",
name => "Chris Cringle",
type => "ft",
location_id => 007,
emp_cat_id => 555
},
{
percentage => 0.25,
code => "XXX",
name => "Tom Thompson",
type => "pt",
location_id => 002,
emp_cat_id => 555
}
]
};
foreach my $arrayref (values %$hashref) {
@$arrayref = sort { $a->{location_id} <=> $b->{location_id} } @$arrayref;
}
print Dumper($hashref);
您缺少的重要部分是取消參考陣列參考。@$arrayref而不僅僅是$arrayref.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386510.html
上一篇:在一行中給出一串數字,用空格分隔
