CIT 042 Index > Program - Modules > Hint

Programming Assignment—Modules: Hint

#
#   Convert a military time in form hhmm to number of
#   minutes past midnight; returns -1 if time is not valid.
#
sub military_to_minutes
{
    my $mil_str = shift;
    my $hr;
    my $min;
    
    ($hr, $min) = $mil_str =~ m/^(2[0-3]|[0-1][0-9])([0-5][0-9])$/;
    if ($hr eq "" &&  $min eq "")
    {
        $hr = 0;
        $min = -1;
    }
    return $hr * 60 + $min;
}

#
#   Convert a civilian time to minutes past midnight;
#   returns -1 if time is not valid.
#
sub civilian_to_minutes
{
    my $civ_str = shift;
    my $hr;
    my $min;
    my $ampm;
    ($hr, $min, $ampm) = $civ_str =~
        m/^(0?[1-9]|1[0-2]):([0-5][0-9])\s*([a|p])(\.?m\.?)?$/i;
    if ($hr ne "" && $min ne "")
    {
        if ($ampm =~ m/p/i)
        {
            $hr += 12;
            $hr = 12 if ($hr == 24);
        }
        else
        {
            $hr = 0 if ($hr == 12);
        }
    }
    else
    {
        $hr = 0;
        $min = -1;
    }
    return $hr * 60 + $min;
}