On Tue, 4 Apr 2006, Mike Blezien wrote:

> I am trying to come up with a function, or formula calculation, to 
> determine the total days of a given month, IE: April which has 30 
> days, Feb has 28 days, March has 31 days... etc
> 
> Is there way to do this with Perl

Don't calculate it. Just use a lookup table in a hash.

Trivially, and not 100% accurate but maybe good enough:

    my %months = (
        jan => 31,
        feb => 28,
        mar => 31,
        apr => 30,
        jun => 30,
        jul => 31,
        aug => 31,
        sep => 30,
        oct => 31,
        nov => 30,
        dec => 31
    );

Depending on what you're doing, you may have to handle leap years. If 
you do, you can do something like this instead:

    if (leap_year($year)) {
        my %months = (
            jan => 31,
            feb => 29,
            ...
        );
    } else {
        my %months = (
            jan => 31,
            feb => 28,
            ...
        );
    }

(In this example, leap_year($year) is left as an exercise. :-)

For a lot of problems like this, where you know that there's a 
one-to-one mapping between things -- as, in this case, months and day 
counts -- the easiest way is just a hash-based lookup table. 

You can often solve these things with some kind of elaborate 
calculations -- say, to compute the day that a lunar-calendar based 
holiday (Easter, Hanukkah, Ramadan, Chinese New Year, etc) -- but a lot 
of the time it ends up being easier to just figure out the mappings in 
advance and hard-code that either in your script or in a resource data 
file that your script loads at run time.


-- 
Chris Devers

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to