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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
help please, search and replace with sequential numbers

 



David4
Deleted

Mar 6, 2000, 10:34 AM

Post #1 of 5 (905 views)
help please, search and replace with sequential numbers Can't Post

Hi,

I'm a Perl beginner. Here's this little program I could not get my expected output.

$Test = '7 apples';
$b = 3;
while($b < 6){
$Test =~ s/7/$b/g;
print "$Test\n";
$b += 1;}


I was expecting to get:
3 apples
4 apples
5 apples

instead I get:
3 apples
3 apples
3 apples

Can you please help me get my expected
output? Thanks!!!


darian
Deleted

Mar 6, 2000, 12:57 AM

Post #2 of 5 (905 views)
Re: help please, search and replace with sequential numbers [In reply to] Can't Post

This should increment it the way you want.

$Test = "7 apples";
$b = 3;
while($b < 6){
$Test =~ s/^7/$b/g;
print "$Test\n";
$b++;
}



japhy
Enthusiast

Mar 6, 2000, 6:22 AM

Post #3 of 5 (905 views)
Re: help please, search and replace with sequential numbers [In reply to] Can't Post

Your pattern doesn't work because after the first replacement, there IS no 7 in your string. You may want to use the \d regex metacharacter, which means "any digit character":

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


$string = "100 apples\n";
$start = 3;
while ($start < 15) {
# change the FIRST occurrence of digits
# to whatever $start holds
$string =~ s/\d+/$start/;
print $string;
$start++;
}
</pre><HR></BLOCKQUOTE>


japhy
Enthusiast

Mar 6, 2000, 7:18 AM

Post #4 of 5 (905 views)
Re: help please, search and replace with sequential numbers [In reply to] Can't Post

Another solution:

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


$string = "7 apples\n";
$start = 3;
while ($start < 6) {
($new = $string) =~ s/7/$start/;
print $new;
$start++;
}
</pre><HR></BLOCKQUOTE>


David4
Deleted

Mar 6, 2000, 11:04 PM

Post #5 of 5 (905 views)
Re: help please, search and replace with sequential numbers [In reply to] Can't Post

OK, I understand all three programs now. Thank you!

 
 


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

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