Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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

by choroba (Cardinal)
on Jan 18, 2022 at 17:46 UTC ( [id://11140572]=note: print w/replies, xml ) Need Help??


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

Dates can be compared as strings if they follow the YYYY-MM-DD pattern (compulsory xkcd reference).
sub mdy2ymd { my ($mdy) = @_; $mdy =~ /(..)-(..)-(....)/ and return "$3-$1-$2"; } my @filtered = sort { mdy2ymd($a->{Date}) cmp mdy2ymd($b->{Date}) } @$data;

For longer lists, you might want to use the Schwartzian transform so Perl doesn't have to convert each date several times.

Better yet, store the dates directly in the YYYY-MM-DD format and you can sort them the way you wanted.

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Get most recent data based on a date from an array of hashes.
by Anonymous Monk on Jan 18, 2022 at 18:04 UTC
    I tried, but still getting all the data instead of the most recent:
    sub mdy2ymd { my ($mdy) = @_; $mdy =~ s/^(\d{1,2})\D(\d{1,2})\D(\d{4}|\d{4}\s+).*/$1\-$2\-$3/; return "$3-$1-$2"; } my @filtered = sort { mdy2ymd($a->{Date}) cmp mdy2ymd($b->{Date}) } @$data; print Dumper @filtered;

      Your sort call just reorders your list, it does nothing to "filter" the contents. You want to take the first last item off the generated list.

      Also it doesn't make much sense to use s/// to modify the string to M-D-Y to then return a different string Y-M-D. Better would be to either use just a match m// and return the new string, or to actually switch things around with the s/// and return the modified string.

      ## Either $mdy =~ m{^(...blahblah...)}; return "$3-$1-$2"; ## Or . . . $mdy =~ s{^(...blahblah...)}{$3-$1-$2}; return $mdy; ## Or maybe (with a new enough perl) return $mdy =~ s{...}{$3-$1-$2}r;

      Edit: Misread the order of comparison being used in the parent sample code.

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

        Yes, but still cant get the result of the most recent date from the array:
        $mdy =~ m{^(\d{1,2})\D(\d{1,2})\D(\d{4}|\d{4}\s+)}; return "$3-$1-$2";

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-03-29 15:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found