2014-01-21 4 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"; 
} 

출력 :

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

substr에서 변수를 어떻게 사용할 수 있습니까? $stringsubstr()의 첫 번째 호출이이 문자열에는 '작업'입니다 후

답변

4

,이 시도 :

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"; 
}