Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Variable on white space [duplicate]

Tags:

split

perl

I'm trying to split a string into an array with the split occurring at the white spaces. Each block of text is seperated by numerous (variable) spaces.

Here is the string:

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

I have tried the following without success.

my @array1 = split / /, $VAR1;

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

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

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

I'd 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 split this?

like image 956
hallert Avatar asked Jun 05 '13 17:06

hallert


People also ask

How do you split in white space?

The standard solution to split a string is using the split() method provided by the String class. It accepts a regular expression as a delimiter and returns a string array. To split on any whitespace character, you can use the predefined character class \s that represents a whitespace character.

How do you split a string in whitespace in Python?

The Pythonic way of splitting on a string in Python uses the str. split(sep) function. It splits the string based on the specified delimiter sep . When the delimiter is not provided, the consecutive whitespace is treated as a separator.


1 Answers

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

my @array1 = split ' ', $VAR1;

(BTW, it is almost equivalent to your last option, but it also removes any leading whitespace.)

like image 52
choroba Avatar answered Sep 19 '22 15:09

choroba