使用perl中的substr删除字符

时间:2015-01-17 19:08:56

标签: perl substr

我正在尝试从字符串

中删除两个字符
This is what you have
使用

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

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

This  what you have

但我希望得到

This what you have

任何人都可以帮助我摆脱那个空间吗?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

字符串与数组一样,从位置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

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

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

答案 2 :(得分:-2)

我不认为您可以为substr命令的结果分配一个字符串,就像您尝试的那样,并获得预期的结果。请尝试这种方式:

$ newstring = substr($ string,0,4)。 SUBSTR($字符串,5);