Search code examples
perlsubstr

How to extract a value from a variable within if condition


I am trying to extract the timestamp portion from the variable, but somehow the substr function isnt working

This is what I have tried

while(<INFILE>){
chomp;
if(/timestamp:(.+$)/){
                        $ts = $1;
                        $ts =~ substr($ts, 10);
print $ts;
}

close(INFILE);

This is how the line is in the file

timestamp: 25JUN2019_02:55:02.234
somedata..
..
..
..

timestamp: 25JUN2019_07:00:28.718

I want the output to be

02:55:02.234
07:00:28.718

But instead the output is

25JUN2019_02:55:02.234
25JUN2019_07:00:28.718

Solution

  • Several issues:

    1. You are using the bind operator =~ instead of the assignment operator =
    2. You should always use strict and use warnings
    3. You should ignore whitespace before your match
    4. If there is additional data on the line, substr will return it as well. You should scope your substr to only include want you want.

    Revised code:

    use strict;
    use warnings;
    
    while(<DATA>) {
      chomp;
      if (/timestamp:\s*(.+$)/) {
        my $ts = substr($1, 10, 12); # only include length of data you want
        print $ts;
      }
    }
    
    __DATA__
    timestamp: 25JUN2019_02:55:02.234
    

    Output:

    02:55:02.234