Discussion Locked

Perl Strings remove whitespace

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Need to remove whitespace from a string like:
12 254 0 19 23
and add it to an array or a scaler as comma separated

6 replies

by apotheon

$foo = 12 254 0 19 23;
$foo ~= s/ /,/g;

That should do it, based on what you said. If you want to replace characters in a string scalar, you'll want to look into using substitution regular expressions. The leading "s" makes it substitution, the space between the first two slashes is what's getting replaced, the comma between the second and third slashes is what's replacing it, and the trailing "g" makes it global (so that it replaces all instances of the space character, rather than just the first one it finds). The "~=" is just shorthand for setting a variable equal to a modified version of the same variable's earlier value.

by apotheon

Er, whoops. Pretend I included quotes in the appropriate place. The first line of that should have read as follows:

$foo = '12 254 0 19 23';

by illilli

Although, it may be irrelavant at this point, if you want to put the data into an array:

$mystring = "12 254 0 19 23";
@arr_mystring = split(/ /, $mystring);

$arr_mystring[0] is equal to "12"
$arr_mystring[1] is equal to "254"
$arr_mystring[2] is equal to "0"
$arr_mystring[3] is equal to "19"
$arr_mystring[4] is equal to "23"

This discussion is closed to new replies.