views:

112

answers:

3

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 character 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.

+1  A: 

Your example does work. The $string will contain MATHATBAT as you wanted to have, the problem is somewhere else, not in this part.

KARASZI István
Thanks, I see it now. I'll dig for the error :) Is there a better way of doing this, do you know? Thanks again!
Bharat
A: 

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

Øyvind Skaar
+3  A: 

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.

M42
That's eye-opening. I guess it being easier to write doesn't make it easier to run or faster :) Thanks!
Bharat