Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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 ( [id://11140574]=note: print w/replies, xml ) Need Help??


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

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;
  • Comment on Re^2: Get most recent data based on a date from an array of hashes.
  • Download Code

Replies are listed 'Best First'.
Re^3: Get most recent data based on a date from an array of hashes.
by Fletch (Bishop) on Jan 18, 2022 at 18:45 UTC

    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";

        If you're sorting $a cmp $b the most recent will be in the last element rather than the first so pull out $sorted[-1] instead. The alternative is to swap the order of comparison ($b cmp $a) and then the most recent will be first.

        #!/usr/bin/env perl use 5.032; my @dates = qw( 02-03-2003 03-01-2015 01-15-2022 ); my @sorted = sort { my $new_a = join( q{-}, (split(/-/,$a))[2,0,1] ); my $new_b = join( q{-}, (split(/-/,$b))[2,0,1] ); $new_b cmp $new_a } @dates; say $sorted[0]; __END__ $ perl blonk.plx 01-15-2022

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 12:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found