在perl中使用substr删除字符

在perl中使用substr删除字符,perl,substr,Perl,Substr,我正在尝试从字符串中删除两个字符 This is what you have 使用 这两个字符将被删除,但留下了一个额外的空间。我得到 This what you have 但我渴望得到 This what you have 有人能帮我去掉那个空格吗?我认为你不能像你试图做的那样,给substr命令的结果分配一个字符串,并得到预期的结果。试着这样做: $newstring=substr($string,0,4)。substr($string,5) 如果要从中删除单词is及其旁边的一个空格

我正在尝试从字符串中删除两个字符

This is what you have
使用

这两个字符将被删除,但留下了一个额外的空间。我得到

This  what you have
但我渴望得到

This what you have

有人能帮我去掉那个空格吗?

我认为你不能像你试图做的那样,给substr命令的结果分配一个字符串,并得到预期的结果。试着这样做:


$newstring=substr($string,0,4)。substr($string,5)

如果要从
中删除单词
is
及其旁边的一个空格,则需要删除3个字符,而不仅仅是2个。

字符串(如数组)从位置0开始:

say '012345679';
my $str = "This is what you have";
say $str;

--output:--
012345679
This is what you have
要删除“is”和“is”前面的空格,需要删除位置4、5、6:

012345679
This is what you have
    ^^^
    |||
…您可以这样做:

say '012345679';
my $str = "This is what you have";
say $str;

substr($str, 4, 3) = "";
say $str;

--output:--
012345679
This is what you have
This what you have
say '012345679';
my $str = "This is what you have";
say $str;

substr($str, 5, 3) = "";
say $str;

--output:--
012345679
This is what you have
This what you have
或者,您可以通过删除位置5、6、7来删除“is”和“is”之后的空格:

012345679
This is what you have
     ^^^
     |||
…就像这样:

say '012345679';
my $str = "This is what you have";
say $str;

substr($str, 4, 3) = "";
say $str;

--output:--
012345679
This is what you have
This what you have
say '012345679';
my $str = "This is what you have";
say $str;

substr($str, 5, 3) = "";
say $str;

--output:--
012345679
This is what you have
This what you have
但是,在perl中,大多数人使用
s//
(替换运算符)进行替换:

s/find me/replace with me/
因此,您可以这样做:

my $str = "This is what you have"; 
say $str;

$str =~ s/\bis\b //;  # \b means 'word boundary'
say $str;

--output:--
012345679
This is what you have
This what you have
perl程序员很懒,计算位置太难了。在大多数情况下,您确实需要知道正则表达式

如果要删除字符串中出现的所有“is”,则可以添加“g”(全局)标志:


substr
可以充当左值,没关系。原始输入是什么?如果你想从“这就是你拥有的”中删除“是”,你只需删除3个字符,而不是2个。谢谢吉姆·戴维斯,你的建议很有效。@JimDavis:请将你的评论作为解决方案发布,以便OP可以接受,并将问题标记为已回答。