2014-01-21 32 views
0

我試圖傳遞變量到SUBSTR ,使得每個時間 '工作' 將被取代 用遞增的數目PERL SUBSTR:使用變量subsitution

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

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

for(my $replace = 0; $replace < 3; $replace++) { 
    if(($idx= index($string, $find)) > -1) { 
     substr($string, $idx, 4, $replace); 
    } 
    print "[#$replace] $string\n"; 
} 

OUTPUT:

[#0] why doesnt this 0? 
[#1] why doesnt this 0? 
[#2] why doesnt this 0? 

如何在substr中使用變量?

回答

4

您的substr()$string第一個電話,這些是在這個字符串中沒有「工作」後,試試這個:

my $find = "work"; 
my $org_string = "why doesnt this work?"; 
my $idx; 

for(my $replace = 0; $replace < 3; $replace++) { 
    my $string = $org_string; 
    if(($idx= index($string, $find)) > -1) { 
     substr($string, $idx, 4, $replace); 
    } 
    print "[#$replace] $string\n"; 
}