1

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.

2
  • 2
    "without the computers array." -- i don't understand? Can you show your expected output? Commented Jul 21, 2021 at 17:03
  • Don't use $a and $b; they are somewhat special and using them outside sort's compare function can cause issues. Commented Jul 22, 2021 at 3:31

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Data::Dump is the simplest of the various data dumpers.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.