views:

105

answers:

3

I want to replace aeiou with bfjpv in user inputted string. Here is the code which is not working :-

print "Enter any String :";
while(($string = <>) ne "\n"){

    @arr = split(//,$string);

    for($i = 0 ; $i < $#arr ; $i++){
        $char = $arr[$i];

        if($char eq 'a' || $char eq 'e' || $char eq 'i' || $char eq 'o' || $char eq 'u'){
            $char = $char + 1;
        }
        print $char;
    }

}

What should I do to add one character? I mean how do I replace a with b.

+4  A: 
$char = chr(ord($char) + 1);

ord = convert character to integer

chr = convert integer to character

Thomas O
@Thomas O : Thank you!
Ankit Rathod
Far too complex. $chr++ does the same thing.
davorg
Yes, but this is far clearer in meaning. What if chr was an integer?
Thomas O
+10  A: 

You can just do

$char++;

in place of

$char = $char + 1;

Also you really don't need to loop to do the replacement. Just use the tr operator as:

($new_string = $string) =~ tr [aeiou] [bfjpv];
codaddict
Great this also works fine and is more readable :)
Ankit Rathod
+7  A: 
$string =~ tr/aeiou/bfjpv/;

Does the whole job. See the perlop manual.

msw