Raj
Raj

Reputation: 51

How to write Regular Expression in perl with generic way

I have written code as:

$body =~ s/Í/Í/g;    
$body =~ s/Ó/Ó/g;    
$body =~ s/Ú/Ú/g;   
$body =~ s/Ý/Ý/g;

But this is not a good way.

Could you please provide a generic solution?

Upvotes: 2

Views: 105

Answers (1)

tchrist
tchrist

Reputation: 80383

This is a solved problem as currently phrased:

use HTML::Entities qw(decode_entities);
$unescaped_body = decode_entities($escaped_body);

If you really want to do arbitrary pairs of in and out, you should set it up as a hash.

my %remap = (
   red   => "rojo",
   white => "blanco",
   blue  => "azul",
);

while (my($from, $to) = each %remap) {
    $text =~ s/\Q$from/$to/g;
}

But that will be slow; there are better ways of doing it, but you probably aren't ready for them yet.

Upvotes: 7

Related Questions