If the date is in YYYY-MM-DD format, then a simple string comparison works fine
my @dates = qw( 2001-12-24 1999-03-2 2004-04-23 ); print join(', ', sort { $b cmp $a } @dates );
prints
2004-04-23, 2001-12-24, 1999-03-2
The whole thing is much simpler if you use grep. In fact, you can find, and set the 'isnext' key in a single line. What you want to find is the smallest date larger than or equal to the given date. First sort the dates in ascending order:
sort { $a->{date} cmp $b->{date} } @$array
then grep out those that are larger than the given date:
grep { $_->{date} ge $today } ...
and the first one of those will be your match:
( ... )[0]->{isnext} = 1;
So the answer goes like this:
(grep {$_->{date} ge $today} sort {$a->{date}cmp $b->{date} } @$array) +[0]->{isnext} = 1;
The whole thing then looks like this:
my $today = '2001-03-28'; my $array = [ { date => '2001-02-01' }, { date => '1999-04-09' }, { date => '2001-03-31' }, { date => '2001-03-24' }, { date => '2001-04-15' }, ]; # find the smallest date larger than or equal to today. # set the isnext flag (grep { $_->{date} ge $today } sort { $a->{date} cmp $b->{date} } @$a +rray)[0]->{isnext} = 1; # print all out and indicate which one is next... for my $e (@$array) { print "\n", $e->{date}; print " this is next" if $e->{isnext}; } # alternatively : my $thenext = (grep { $_->{date} ge $today } sort { $a->{date} cmp $b- +>{date} } @$array)[0]; print "\nThe next date is: $thenext->{date}\n";

In reply to Re: Re: Finding array element by Vondikall
in thread Finding array element by voyager

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.