my $num_ent_chars = "()"; # add other characters as needed, but ^ - [ ] are special $data =~ s/([$num_ent_chars])/sprintf("&#x%4x;",ord($1))/ge;