Perl parsing and difference calculations for "plus days: hours: minutes"

I have a line with a time difference like:

12:03:22  <- where
 ^  ^  ^
 |  |  +minutes
 |  +hours
 +days

Mandatory - this is only minutes, hours and days can be omitted, but here it can be, for example, 120: 30, therefore 120 hours and 30 minutes.

You need to calculate the date and time for NOW + the difference , for example:

when now is "May 20, 13:50" and
the string is "1:1:5"
want get as result: "2012 05 21 14 55" (May 21, 14:55)

I know DateTime, but what is an easy way to parse an input string? I am sure there is a better way:

use _usual_things_;
my ....
if($str =~ m/(.*):(.*):(.*)/) {
   $d = $1; $h = $2; $m = $3;
}
elsif( $str =~ m/(.*):(.*)/ ) {
   $h = $1; $m = $2;
} elsif ($str =~ m/\d+/ ) {
   $m = $1;
}
else {
  say "error";
}

And how to add the parsed days, hours, minutes to the course date?

+3
source share
2 answers

How to use reverseto avoid format validation?

my ($m, $h, $d) = reverse split /:/, $str;

To add this to the current date, simply use DateTime:

print DateTime->now->add(days    => $d // 0,
                         hours   => $h // 0,
                         minutes => $m);
+8
source

, . . .

$Str = '12:03:22' ;

@Values = ($Str=~/\G(\d\d):?/g) ;

print "error with input" if not @Values;

if( @Values == 3) { print "Have all 3 values\n" }
elsif( @Values == 2) { print "Have 2 values\n" }
-1

All Articles