----- Original Message -----
From: Venkat Saranathan
Newsgroups: perl.beginners
To: Johnson, Reginald (GTS)
Cc: beginners@perl.org
Sent: Tuesday, December 22, 2009 10:27 AM
Subject: Re: Saturdays in a month
You can code a simple time logic to calculate this. Here is a sample code.
(Bugs included :))
#!/usr/bin/perl
use Time::Local;
use strict;
sub day_in_a_month {
my ($week_day, $month, $year ) = @_;
my ($day, $hour, $min, $sec, $time);
my ($mon, $wday_count);
$day = 1;
$hour = $min = $sec = 0;
$month--;
$year -= 1900;
$time = timelocal($sec, $min, $hour, $day, $month, $year);
for ($mon = $month; $mon == $month; $time += 86400) {
my ($wday);
($mon, $wday) = (localtime($time))[4, 6];
if ($wday == $week_day) {
$wday_count++;
}
}
return($wday_count);
}
# 0 - sunday 6- saturday
print day_in_a_month(6, 12, 2009), "\n";
Hello Venkat,
There is a bug in the the 'for' loop above. :-)
The test to end the loop has to occur just after the line
($mon, $wday) = (localtime($time))[4, 6];
Otherwise, it would be possible to be in a new month at this point in the
code. If the day of week you're seeking is that day, $wday_count would be
incorrectly incremented. Try adding this line after the one above:
last unless $mon == $month;
That will allow you to exit the loop when a new month is reached. The for
loop could then be:
for (;;$time += 86400) {
.............
}
However, I have heard it over and over from good programmers on lists that
date arithmetic can be tricky. Sometimes a carefully designed module can
help.
Chris
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/