Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Get most recent data based on a date from an array of hashes.

by johngg (Canon)
on Jan 19, 2022 at 00:30 UTC ( #11140599=note: print w/replies, xml ) Need Help??


in reply to Get most recent data based on a date from an array of hashes.

You can use Time::Piece (which is core) to get the epoch seconds from the date. The epoch key/value pair can then be added to the hash ref. for sort'ing numerically and then delete'ed from the hash ref. afterwards. You can then take the last element from the sorted items to get the latest date.

use strict; use warnings; use Time::Piece; use Data::Dumper; my $data = [ { Color => q{green}, Step => q{Platform}, acc => q{1111}, Date => q{08-06-2022}, }, { Color => q{black}, Step => q{Platform}, acc => q{1111}, Date => q{01-05-2019}, }, { Color => q{blue}, Step => q{Platform}, acc => q{1111}, Date => q{10-11-2020}, }, { Color => q{white}, Step => q{Platform}, acc => q{1111}, Date => q{01-03-2022}, }, { Color => q{red}, Step => q{Platform}, acc => q{1111}, Date => q{03-21-2021}, }, ]; my @filtered = ( map { delete $_->{ epoch }; $_; } sort { $a->{ epoch } <=> $b->{ epoch } } map { $_->{ epoch } = Time::Piece->strptime( $_->{ Date }, q{%m-%d-%Y} )->epo +ch(); $_; } @{ $data } )[ -1 ]; print Data::Dumper->Dumpxs( [ \ @filtered ], [ qw{ *filtered } ] );

Produces

@filtered = ( { 'Color' => 'green', 'Date' => '08-06-2022', 'Step' => 'Platform', 'acc' => '1111' } );

I hope this is helpful.

Update: Expanded wording re. use of the temporary epoch key/value pair.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Get most recent data based on a date from an array of hashes.
by AnomalousMonk (Archbishop) on Jan 19, 2022 at 21:38 UTC
    my @filtered = ( ... )[ -1 ];

    Since the @filtered array cannot be more than a single element, wouldn't it be better to make this a scalar?
        my $most_recent = ( ... )[ -1 ];

    This would have the possibly desirable side effect that if the input array were empty, $most_recent would be undefined/false. (It must be defined/true otherwise because it would be a reference.)


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140599]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2023-09-24 06:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?