在 perl 中使用 substr 删除字符

removing character using substr in perl

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

This is what you have

使用

substr ($string, 5, 2) = "";

这两个字符将被删除,但会留下一个额外的 space。我获得

This  what you have

但我想得到

This what you have

谁能帮我摆脱那个space?

我认为您无法像您尝试的那样将字符串分配给 substr 命令的结果,并获得预期的结果。改用这种方式试试:

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

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

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

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

--output:--
012345679
This is what you have

要删除 'is' 和 'is' 之前的 space,您需要删除位置 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

或者,您可以通过删除位置 5、6、7 来删除 'is' 和 'is' 之后的 space:

012345679
This is 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'(全局)标志:

my $str = "This is what you have, but his hat is black isn't it?";
say $str;

$str =~ s/\bis\b //g;
say $str;

--output:--
This is what you have, but his hat is black isn't it?
This what you have, but his hat black isn't it?
  ^                      ^            ^
  |                      |            |
    skips 'is' embedded in other words