Seitenanfang

Age check with Perl

Dieser Post wurde aus meiner alten WordPress-Installation importiert. Sollte es Darstellungsprobleme, falsche Links oder fehlende Bilder geben, bitte einfach hier einen Kommentar hinterlassen. Danke.


Kids are discriminated for being kids. They're not allowed to smoke, drink alcohol and use various internet offers. but writing "not for kids" on a homepage barely fulfills legal and real life requirements, software has to calculate the age based on a known date of birth.

mySQL has a DATE_INTERVAL command but should be considered very bad style to submit simple math issues to the database unless you need to fetch some stored data. Better use Date::Calc and pure Perl:

use Date::Calc qw(Today date_check N_Delta_YMD);

=pod

=head2 calculate_age

$age = calculate_age($date_of_birth);

Return the current age based on the given date of birth (YYYY-MM-DD).

Sample:

calculate_age('1979-08-20');

Returns 33 (at least today).

=cut

sub calculate_age my @dob = split(/\-/, shift);

# Check if given date of birth is valid. return unless check_date(@dob);

# Calculate the years, months and days since the given date of birth my @age = N_Delta_YMD(@dob, Today());

return $age[0];}

check_date is strongly suggested because all (other) Date::Calc functions will die in case of any invalid date passed.

 

6 Kommentare. Schreib was dazu

  1. Jay

    Or use Time::Piece + Time::Seconds (part of core since 5.10)

  2. [Imported from blog]

  3. [Imported from blog]

  4. I only ever use Time::Piece or DateTime for time and date calculations these days.



    #!/usr/bin/perl


    use strict;
    use warnings;
    use 5.010;
    use Time::Piece;


    say calculate_age('1979-08-20');


    sub calculate_age {
    my $dob = Time::Piece->strptime(shift, '%Y-%m-%d');
    my $age = Time::Piece->localtime - $dob;


    return int $age->years;
    }

  5. [Imported from blog]

  6. [Imported from blog]

Schreib was dazu

Die folgenden HTML-Tags sind erlaubt:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>