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 |