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?
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With