CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
Character substitution



Jan 29, 2000, 1:49 PM

Post #1 of 2 (1622 views)
Character substitution Can't Post

I have a scalar variable which has comma separated lists of references. Now some of the users have input the data putting spaces before the commas, some after and some not at all. So I want to remove all spaces from the variable before I start processing it. I've tried $refs =~ s/ *//; which I thought said "substitute from 0 to infinity spaces with a null". I've obviously messed up - but how?


Jan 29, 2000, 2:32 PM

Post #2 of 2 (1622 views)
Re: Character substitution [In reply to] Can't Post

Well, the s/ *// regex will remove the FIRST and LONGEST occurrance of 0 or more spaces. Let me show you something that will boggle your mind:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

$string = "fred xxxxxx barney";
$string =~ s/x*//;
print $string; # "fred xxxxxx barney"

What?! Why didn't it remove the x's in the middle? Well, because the first occurrance of 0 or more x's is right at the beginning of the string. Can't you see the 0 x's before the "f" of "fred"? So it removes those x's, all 0 of them.

What you probably want is s/ +//. Or even better, s/ +//g. The + means 1 or more, so that won't match 0 spaces. And the /g means do this for all sets of 1 or more spaces.

Even better is the use of tr///. tr/ //d will remove all spaces, and do so quickly.

Read the perlre documentation for information on s/// and tr///.


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives