PERL substr:使用变量替换

时间:2014-01-21 10:17:13

标签: perl

我正在尝试将变量传递给substr 这样每次“工作”都会被取代 增加数字

#!/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中使用变量?

1 个答案:

答案 0 :(得分: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";
}