Divide the variable by space

I am trying to split a string into an array with the split occurring in white spaces. Each block of text is divided by numerous (variable) spaces.

Here is the line:

NUM8 host01 1,099,849,993 1,099,849,992 1 

I tried the following without success.

 my @array1 = split / /, $VAR1; my @array1 = split / +/, $VAR1; my @array1 = split /\s/, $VAR1; my @array1 = split /\s+/, $VAR1; 

I would like to end up with:

 $array1[0] = NUM8 $array1[1] = host01 $array1[2] = 1,099,849,993 $array1[3] = 1,099,849,992 $array1[4] = 1 

What is the best way to share this?

Thanks!

+8
split perl
source share
3 answers

If the first argument to split is the string '' (space), it is special. It must match a space of any size:

 my @array1 = split ' ', $VAR1; 

(BTW, this is almost equivalent to your last option, but also removes all leading spaces.)

+21
source share

Just try using:

 my @array1 = split(' ',$VAR1); 

Codepad Demo

From Perldoc :

As another special case, splitting emulates the default behavior for the awk command-line tool when PATTERN is either omitted or literally a string consisting of a single space character (for example, '' or '\ x20 ", but not, for example, //). In this case, any leading spaces in EXPR are removed before splitting.

+9
source share

\s+ matches 1 or more spaces and breaks into them

 my @array1 = split /\s+/, $VAR1; 
+4
source share

All Articles