I am
I am

Reputation: 1067

Substitution of characters in Perl

I am working on doubling all vowels in every word. For eg:

$string="if it rains, cover with umbrella";

Here is the code I wrote, but I am not getting correct output.

$string=~s/a|e|i|o|u/aa|ee|ii|oo|uu/gi; print $string;

Expected Output: iif iit raaiins cooveer wiith uumbreelaa

Can some one help me in this?

Upvotes: 3

Views: 261

Answers (4)

Borodin
Borodin

Reputation: 126722

The regular expression in your substitution should work fine but, as you will have seen, the replacement string is a simple string that bears no relation to the match unless you capture substrings within the regular expression and use them in the replacement string.

Use a character class to match any one of a set of characters, like [aeiuo].

Use parentheses to 'capture' part of a match, so that you can use it in the replacement string.

my $string = "if it rains, cover with umbrella";

$string =~ s/([aeiuo])/$1$1/g;

print $string;

output

iif iit raaiins, cooveer wiith uumbreellaa

Upvotes: 8

ikegami
ikegami

Reputation: 385754

As previously mentioned, the following would do the trick in this circumstance:

s/([aeiuo])/$1$1/ig;    # A => AA

Or maybe you want

s/([aeiuo])/\L$1$1/ig;  # A => aa

The following is an alternative solution that works for arbitrary translation maps:

my %map = (
   'a' => 'aa',
   'e' => 'ee',
   'i' => 'ii',
   'o' => 'uu',
   'u' => 'oo',
);

my $pat =
   join '|',
    map quotemeta,
     sort { length($b) <=> length($a) }
      keys(%map);

s/($pat)/$map{$1}/g;

The above even works if you have

( 'foo' => 'bar',
  'bar' => 'foo' )

The sort line can be omitted if you don't have something like

( 'foo'  => 'bar',
  'food' => 'baz' )

Upvotes: 1

Rob Volgman
Rob Volgman

Reputation: 2114

You didn't print what the incorrect output was, but you can simply replace each vowel with its double. For example:

$string =~ s/a/aa/g;
$string =~ s/e/ee/g;
$string =~ s/i/ii/g;
$string =~ s/o/oo/g;
$string =~ s/u/uu/g;

Upvotes: 0

hackattack
hackattack

Reputation: 1087

All matches are captured in variables $1,...,$9, so if you substitute $1 twice it will repeat whatever the match is, in this case it will double up vowels

$string=~ s/(a|e|i|o|u)/\1\1/gi; 
print $string;

Upvotes: 3

Related Questions