我有变量$pos
,$toRemove
和$line
。我想从位置$toRemove
中删除此字符串$pos
。
$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30; # the 3rd 'kitty'
我想检查位置30是否有字符串kitty
,我想要删除这一个。
你能给我一个解决方案吗?我可以使用很多循环和变量来做它但它看起来很奇怪并且工作得非常慢。
答案 0 :(得分:6)
if (substr($line, $pos, length($toRemove)) eq $toRemove) {
substr($line, $pos, length($toRemove)) = "";
}
答案 1 :(得分:3)
$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30; # the 3rd 'kitty'
pos($line) = $pos;
$line =~ s/\G$toRemove//gc;
print $line;
输出:
Hello kitty how are you kitty nice kitty
答案 2 :(得分:2)
另一种方式:
$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30;
$line =~ s/(.{$pos})$toRemove/$1/;
print $line;
结果:
Hello kitty how are you kitty nice kitty
答案 3 :(得分:2)
$line =~ s/^.{30}\K$toRemove//;
这使用一个后面的断言来匹配前30个字符,而不将它们包含在被替换的模式部分中。
答案 4 :(得分:1)
[pos
] [pos]运算符只是这种事情的左值:
[pos]:
use strict;
use warnings;
my $line = "Hello kitty how are you kitty kitty nice kitty";
my $toRemove = "kitty";
my $pos = 30;
pos($line) = $pos;
$line =~ s/\G$toRemove//;
print $line;
<强>输出强>
Hello kitty how are you kitty nice kitty