Perl cut exact part of the string and store the first delimiter

Viewed 105

Let say I have a variable in this format:

my $time1 = "2021-01-02T11:12:00+01:00";

I would like to get the part of the string from + or the last - to the last : and also the first delimiter which should be a + or -

What I tried so far:

print (split(/\+/, $time))[0];

but it will then print:

01:00

instead of:

01

and also doesn't store the first delimiter.

3 Answers

You can use regular expressions to extract that type of information more easily:

my $time1 = "2021-01-02T11:12:00+01:00";
($hourpart) = ($time1 =~ /.*[+-](\d{2}):\d{2}$/);
print($hourpart,"\n");

(you can use split too, but it would require multiple split calls)

If you're positive that the length won't change (often true for fixed format date strings), you can try substr instead too:

print(substr($time1, 20, 2),"\n");

Since you are parsing an ISO 8601 datetime string, you might consider using something that is smart about datetime strings.

Date::Parse can give you the timezone offset in seconds and you can convert that to integer hours (or whatever else you might want to do):

use v5.10;
use Date::Parse;

my $datetime = '2021-01-02T11:12:00-01:30';

my @t = Date::Parse::strptime( $datetime );

say "Time zone offset in seconds: $t[-2]";
printf '%02d', abs($t[-2])/3600;

Otherwise, Wes's answer is probably what I'd do.

Please investigate following code snippet which with split fills a hash. Then you can access any part of timestamp as your heart desires.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $time1 = "2021-01-02T11:12:00+01:00";

my $date_time;
my @fields = qw/year month day hour minute second hour_tz minute_tz/;

$date_time->@{@fields} = split("[-+:T]",$time1);

say "Timestamp: " . $time1;
say Dumper($date_time);

my $tz;
$tz->@{qw/sign hour minute/} = $time1 =~ /([-+])(\d+):(\d+)\z/;

say Dumper($tz);

Output

Timestamp: 2021-01-02T11:12:00+01:00
$VAR1 = {
          'second' => '00',
          'day' => '02',
          'hour_tz' => '01',
          'year' => '2021',
          'minute' => '12',
          'hour' => '11',
          'month' => '01',
          'minute_tz' => '00'
        };

$VAR1 = {
          'hour' => '01',
          'sign' => '+',
          'minute' => '00'
        };
Related