General discussion

Locked

Perl Strings remove whitespace

By bmayfield001 ·
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

This conversation is currently closed to new comments.

6 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

by apotheon In reply to Perl Strings remove white ...

$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.

Collapse -

by apotheon In reply to

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';

Collapse -

by bmayfield001 In reply to

Poster rated this answer.

Collapse -

by illilli In reply to Perl Strings remove white ...

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"

Collapse -

by bmayfield001 In reply to

Poster rated this answer.

Collapse -

by bmayfield001 In reply to Perl Strings remove white ...

This question was closed by the author

Back to Web Development Forum
6 total posts (Page 1 of 1)  

Related Discussions

Related Forums