V. Kookie V. Kookie - 2 months ago 14
Perl Question

split white spaces using perl

I have this line of code to split the white spaces in a text file:

my @line_splits = split /\s+/, $ine;


And this is the few contents of the text file:

1 2016-09-27 14:07:20.084877
2 2016-09-27 14:07:20.084998
3 2016-09-27 14:07:20.131343
4 2016-09-27 14:07:20.131374
6 2016-09-27 14:07:20.137359
7 2016-09-27 14:07:20.137556
8 2016-09-27 14:07:20.137796
9 2016-09-27 14:07:20.437769
10 2016-09-27 14:07:20.437796
100 2016-09-27 14:07:23.293661


My goal is to get the date and the time (which I knew is on $line_splits[1] and $line_splits[2]).

But when I ran my perl script, the lines from 1 to 99 are wrong while on the 100th and up I've got what I've want.

Time Stamp: 98 2016-09-27 --> line 98
Time Stamp: 99 2016-09-27 --> line 99
Time Stamp: 2016-09-27 14:07:23.293661 --> line 100
Time Stamp: 2016-09-27 14:07:23.299406 --> line 101
Time Stamp: 2016-09-27 14:07:23.299437 --> line 102


Can someone tell me if what is wrong with the regex or there is another way to do this?

I don't know if it is already duplicated in here but any help will be very much appreciated.

Thank you :)

Answer

Wow, lots of complicated answers, but the solution's really easy.

Just use split without the /\s+/ regex.

The default behaviour - or what you get if you specify just ' ' to split - is that it ignores leading whitespace. But with /\s+/ it doesn't.

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

while ( <DATA> ) {
  chomp;
  my @fields  = split;
  print $fields[2],"\n"
}

__DATA__
  1 2016-09-27 14:07:20.084877
  2 2016-09-27 14:07:20.084998
  3 2016-09-27 14:07:20.131343
  4 2016-09-27 14:07:20.131374
  6 2016-09-27 14:07:20.137359
  7 2016-09-27 14:07:20.137556
  8 2016-09-27 14:07:20.137796
  9 2016-09-27 14:07:20.437769
 10 2016-09-27 14:07:20.437796
100 2016-09-27 14:07:23.293661