0

$args[0] is a reference to a string containing one or more times. I am shifting each time by a variable number of seconds, but then I need to find a way to store (replace) the changed times back into the original string. Any help is appreciated. Here is roughly what I am working with:

    my $TIMEREGEX = qr/(\d{2}:\d{2}:\d{2}\.\d{3}|\d{2}:\d{2}:\d{2})/x;
    if ( my @sTime = ${$args[0]} =~ /$TIMEREGEX/g )
    {
        warn "\ttime(s) found @sTime\n" if $main::opt{d};
        for my $i ( 0..$#sTime )
        {
            $sTime[$i] =~ /(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?/;
            my $epoch_time = ( $1 * 3600 ) + ( $2 * 60 ) + $3;
            $epoch_time += $epoch_shift;
            my @f;
            $f[0] = $epoch_time % 86400 / 3600; # hours
            $f[1] = $epoch_time % 3600 / 60;    # minutes
            $f[2] = $epoch_time % 60;           # seconds
            my $save = $sTime[$i];
            $sTime[$i] = sprintf ( "%02d:%02d:%02d", $f[0], $f[1], $f[2] );
            $sTime[$i] .= $4 if defined ( $4 );
            warn "\tTimeShift $save => $sTime[$i]\n" if $main::opt{d};
            ### some other stuff
        }

        # ${$args[0]} = "$1$t[0]$4$t[1]$7$t[2]$10";
        ### save the changes to ${$args[0]} !

    }
3
  • maybe you looking for s///? and also use s///e with e-key. Commented Apr 23, 2012 at 10:57
  • 1
    or look to split function and join function. they will make your work more simple ;) Commented Apr 23, 2012 at 10:58
  • 3
    Why not use a module that can handle time for you? Like DateTime or Time::Piece. Commented Apr 23, 2012 at 10:59

1 Answer 1

2

Use the substitution operator.

use 5.010;  # or better for 'say' and '//'
use strictures;
use Time::Piece qw();

my @args; my $epoch_shift = 500;
${$args[0]} = 'foo18:00:00.123bar18:00:00baz18:00:00quux';

${$args[0]} =~
    s{
        (\d{2}:\d{2}:\d{2})  # capture hh:mm:ss
        (\.\d{3})?           # optionally capture
                             #   decimal dot and milliseconds
    }
    {
        (
            $epoch_shift
            + Time::Piece->strptime($1, '%T')
        )->strftime('%T').($2 // '')
    }egx;
say ${$args[0]};
# foo18:08:20.123bar18:08:20baz18:08:20quux
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! didn't occur to me to use an expression inside a substitution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.