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:
using loop variable in regex subsitution

 



meir
New User

Jan 21, 2014, 12:38 AM

Post #1 of 2 (760 views)
using loop variable in regex subsitution Can't Post


Code
#!/usr/bin/perl -w 
use strict;

my $find = "work";
my $replace ;
my $string = "why doesnt this work?";

for($replace = 0; $replace < 3; $replace++) {
print "string before regex = $string\n";
$string =~ s/$find/$replace/;
print "string after regex = $string\n";
}


I get result:
string before regex = why doesnt this work?
string after regex = why doesnt this 0?
string before regex = why doesnt this 0?
string after regex = why doesnt this 0?
string before regex = why doesnt this 0?
string after regex = why doesnt this 0

instead of the loop index being inserted into string
any ideas ? Thx


BillKSmith
Veteran

Jan 21, 2014, 5:21 AM

Post #2 of 2 (744 views)
Re: [meir] using loop variable in regex subsitution [In reply to] Can't Post

It does work! After the first substitution, there is no 'work' left to replace.

Perhaps this is what you mean


Code
use strict; 
my $find = "work";
my $replace;
for ( my $replace = 0; $replace < 3; $replace++ ) {
my $string = "why doesnt this work?";
print "string before regex = $string\n";
$string =~ s/$find/$replace/;
print "string after regex = $string\n";
}


Output:

Code
string before regex = why doesnt this work? 
string after regex = why doesnt this 0?
string before regex = why doesnt this work?
string after regex = why doesnt this 1?
string before regex = why doesnt this work?
string after regex = why doesnt this 2?

Good Luck,
Bill

(This post was edited by BillKSmith on Jan 21, 2014, 5:43 AM)

 
 


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

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