steph_bow has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I am doing some computation on numbers but I get strange results, because the "0" seem to disappear. Have you got some hint ? Thanks a lot !

#! perl -slw use strict; use diagnostics; use Data::Dump qw[ pp ]; my $diff = 15; while (<DATA>){ my $former_time = substr($_, 0, 4); my $former_hour = substr($_, 0, 2); my $former_mn = substr($_, 2, 2); my $new_hour = $former_hour; my $new_mn = $former_mn + $diff ; if ($new_mn >= 60){ $new_mn = $new_mn - 60; $new_hour = $new_hour + 1; } # cas où $diff est suffisamment négatif pour faire basculer dans l +'heure d'avant elsif ($new_mn < 0){ $new_mn = $new_mn + 60; $new_hour = $new_hour - 1; } my $new_time = "$new_hour"."$new_mn"; print STDOUT "former_time is $former_time"; print STDOUT "new time is $new_time"; } __DATA__ 1250 0549 1103 1509 0423 0834

Replies are listed 'Best First'.
Re: problem of configration
by cdarke (Prior) on Nov 27, 2008 at 17:11 UTC
    The zero was dropped on the conversion from string to int - a leading zero on an int actually means octal. To put it back use sprintf or printf with a format of something like %04s. For example:
    printf STDOUT "former_time is %04d\n", $former_time;

    Update: And:
    my $new_time = sprintf("%02d%02d", $new_hour, $new_mn);
Re: problem of configration
by oko1 (Deacon) on Nov 28, 2008 at 02:58 UTC

    You might be better off using a module; that way, you don't have to deal with all the edge cases.

    #!/usr/bin/perl -w use strict; use Time::Simple; for (<DATA>){ s/(..)$/:$1/; my $former_time = Time::Simple->new($_); my $new_time = $former_time + 15 * 60; print "former_time is $former_time\nnew time is $new_time\n"; } __DATA__ 1250 0549 1103 1509 0423 0834

    Output:

    former_time is 12:50:00 new time is 13:05:00 former_time is 05:49:00 new time is 06:04:00 former_time is 11:03:00 new time is 11:18:00 former_time is 15:09:00 new time is 15:24:00 former_time is 04:23:00 new time is 04:38:00 former_time is 08:34:00 new time is 08:49:00

    --
    "Language shapes the way we think, and determines what we can think about."
    -- B. L. Whorf
Re: problem of configration
by eye (Chaplain) on Nov 28, 2008 at 06:59 UTC
    Both previous posters make good points. That said, if you want to fix your code rather than using a module, you have another problem. Your code does not handle the rollover of hours (as it does for minutes). It can all be handled with modulo math. Here is a streamlined version of your while loop with the suggested approach to computing the new time:
    while (<DATA>){ my $former_hour = substr($_, 0, 2); my $former_mn = substr($_, 2, 2); my $new_hour = ($former_hour + int($diff / 60)) % 24; my $new_mn = ($former_mn + $diff) % 60; print STDOUT "former_time is $former_hour$former_mn\n"; print STDOUT "new time is $new_hour$new_mn\n"; }
    Note that I have added line feeds to the print statements.