Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to increment a date between a user defined beginning date and end date using nested for loops. This is what I have tried:
for ($m = $beg_month; $m <= $end_month; $m++) { if ($m = "1") { $days = "31"} # to specify days in month if ($m = "2") { $days = "28"} . . . . if ($m = "12") { $days = "31"} for ($d = 1; $d < $days; $d++) { print "$m-$d-$year"; # year is inputed as well } }
Please help. I cannot get this right.

Replies are listed 'Best First'.
Re: Nested For Statement
by Aristotle (Chancellor) on Oct 14, 2002 at 13:58 UTC

    Date::Calc and/or Date::Manip would do what you want correctly (incl minding leap years and all the hooha with dates). The first has an Add_Delta_Days routine which should be exactly what you want.

    In which way does your question specifically relate to nested for loops, other than that you're using them, btw? I don't see anything wrong with them per se.

    Makeshifts last the longest.

Re: Nested For Statement
by Jasper (Chaplain) on Oct 14, 2002 at 14:07 UTC
    Basically your code should work, IF your increment doesn't take you over a month boundary. Then it'll screw up. The code needs a test to make sure the day isn't greater than the end_day (if I'm interpreting the problem correctly) only if the month is the end_month.

    Something like:
    for ($d = $beg_day; ($d <= $end_day && $m == $end_month) || ($m != $en +d_month && $d <= $days); $d++) {
    And inside the second for loop, you'd have to reset beg_day to 1.

    Of course, none of this will work because you have assignments instead of equality tests for the months.
    # if ($m = "12") { $days = "31"} if ($m == 12) { $days = 31 }
    And since this is Perl, those c-style for loops are just ugly.

    And also since this is Perl, someone has already done it. In this case, that someone is Marty Pauley, and you can find the wonderful Date::Simple on the CPAN.

    This provides a super interface for manipulating dates.

    Jasper

    additional: why does
    for ($d = $beg_day; $month == $end_month ? $d <= $end_day : $d <= $day +s; $d++) {
    not work? It looks to me like it should?

    additional, additional: Did somebody say use strict; ? (There is no $month - a change to $m makes it work)

    And of course, this is limiting the whole thing to a single year. One more reason to use someone else's module.