printsmy @dates = qw( 2001-12-24 1999-03-2 2004-04-23 ); print join(', ', sort { $b cmp $a } @dates );
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:2004-04-23, 2001-12-24, 1999-03-2
then grep out those that are larger than the given date:sort { $a->{date} cmp $b->{date} } @$array
and the first one of those will be your match:grep { $_->{date} ge $today } ...
So the answer goes like this:( ... )[0]->{isnext} = 1;
The whole thing then looks like this:(grep {$_->{date} ge $today} sort {$a->{date}cmp $b->{date} } @$array) +[0]->{isnext} = 1;
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |