How can I remove a specific character from a string in Perl?
I'm trying to remove a specific character from a string in Perl:
my $string="MATTHATBAT";
substr($string, 2, 1, '');
EDIT: This does work, sorry. Leaving this here in case someone needs to know how to do this.
Also, is there a more efficient way of doing this?
The string should now be MATHATBAT.
Am I missing something? I know that I can use regex s///, but I am iterating through the string, looking for a certain character (this char changes), then removing the character (but only that ch开发者_开发知识库aracter at that offset). So eventually, I will be removing the second or third occurence of the character (i.e. MATTHABAT, MATTHATBA and even MATHABAT etc)
Can I maybe do this using search and replace? I am using a for loop to iterate through offsets.
Here is a benchmark comparing regexp vs substr:
#!/usr/bin/perl
use 5.10.1;
use warnings;
use strict;
use Benchmark qw(:all);
my $count = -3;
my $r = cmpthese($count,
{
'substring' => sub {
my $string = "MATTHATBAT";
substr($string, 2, 1, '');
},
'regexp' => sub {
my $string = "MATTHATBAT";
$string =~ s/(.{2})./$1/;
},
}
);
Result:
Rate regexp substring
regexp 162340/s -- -93%
substring 2206122/s 1259% --
As you can see, substr is about 13.5 times as fast as regex.
@Sinan Ünür 1259% is 13.5 times and not 12.5 times.
Your example does work. The $string
will contain MATHATBAT
as you wanted to have, the problem is somewhere else, not in this part.
You can loop the reg.exp matches with //g
from perlrequick :
$x = "cat dog house"; # 3 words
while ($x =~ /(\w+)/g) {
print "Word is $1, ends at position ", pos $x, "\n";
}
think you can modify $x while iterating .. or you could store pos $x in an array and remove then afterwards
精彩评论