Reputation: 509
I have a variable that looks like this:
do {
my $a = {
computers => [
{
report_date_epoch => 1591107993595,
serial_number => "C02YK1TAFVCF",
username => "fake1\@example.com",
},
{
report_date_epoch => 1626877069476,
serial_number => "C03XF8AWJG5H",
username => "fake2\@example.com",
},
...
And I'd like to sort it by the epoch number into a new variable without the computers
array.
Upvotes: 1
Views: 171
Reputation: 385976
Sort::Key is so much cleaner than the builtin sort
. Not much difference in this instance, but it only gets better as the task becomes more complex.
use Sort::Key qw( ikeysort );
my @by_report_date =
ikeysort { $_->{report_date_epoch} } # Sort them.
@{ $a->{computers} }; # Get the elements of the array of computers.
Upvotes: 0
Reputation: 66901
The list of hashrefs in the arrayref for computer
key sorted
use warnings;
use strict;
use feature 'say';
use Data::Dump qw(dd);
my $v = {
computers => [
{
report_date_epoch => 1591107993595,
serial_number => "C02YK1TAFVCF",
username => "fake1\@example.com",
},
{
report_date_epoch => 1626877069476,
serial_number => "C03XF8AWJG5H",
username => "fake2\@example.com",
}
]
};
my @by_epoch =
sort { $a->{report_date_epoch} <=> $b->{report_date_epoch} }
@{$v->{computers}};
dd $_ for @by_epoch;
I use Data::Dump to print complex data structures. (There are other good ones as well.)
Or use a core (installed) tool
use Data::Dumper;
...
say Dumper $_ for @by_epoch;
Upvotes: 5