Dawid P Dawid P - 5 months ago 10x
Perl Question

Convert HH:MM into decimal hours

I am trying to convert some time stamps from text file in format HH:MM into number format (for example,

)1 using a Perl regex for easier processing in future.

I am quite new in this topic so I am struggling with MM part and I don't know how to convert it. Currently I have something like this:

while ( <FILE> ) {
$line = $_;
$line =~ s/([0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/$2,$1/g;
print $line;

1) In my locale, the comma
is used for decimal points. Imagine a
So this means 12 and a half, or 12.5.


You only have to adjust the substitution tomake it work:

$line =~ s/(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/"$1," . substr( int($2)\/60, 2)/eg;

The e modifier causes the substituting content to be eval'ed, thus you can write the intended result as kind of a formula contingent on the capture group contents. Note that the substr call eliminates the leading 0, in the string representation of fractions.

If you need to limit your self to a given number of fraction digits, format the result of the division using sprintf:

$line =~ s/(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])/"$1," . substr( sprintf('%.2f', int($2)\/60), 2)/eg;