soumyapanda has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to replace all special characters in my data to its corresponding unicode value by using search and replace as follows

$data = "data ý ¶ data"; $data =~ s/([^\w\`\~\!\@\#\$\^\&\*\(\)\-\_\=\+\[\{\]\}\\\|\;\:\'\,\<\. +\>\/\?\x22\xA0\s\x25\xA9\xA7])/ord($1)/g;

But the output is : data ord(ý) ord(¶) data

Please suggest as how do we use ord as function in search and replace.Thanks

Replies are listed 'Best First'.
Re: replace special character with its unicode
by choroba (Cardinal) on Nov 14, 2011 at 17:07 UTC
    Also note that many characters do not have to be backslashed inside the square brackets.
Re: replace special character with its unicode
by Anonymous Monk on Nov 14, 2011 at 11:45 UTC

    Please suggest as how do we use ord as function in search and replace.

    Use the flag for which is documented to evaluate the right-hand side as code

    It is e

      To clarify the above answer, the flags are after the final / in the regex, where you have already put the g

      as in s/\"/ord($1)/ge

      perl -e 'print qq(Just another Perl Hacker\n)' # where's the irony switch?
Re: replace special character with its unicode
by ikegami (Patriarch) on Nov 14, 2011 at 19:23 UTC
    $data =~ s{ ([^\w\s\xA0~!@#$%^&*\-_=+()[\]{}|;:'`",<.>/?\xA9\xA7]) }{ sprintf "{U+%04X}", ord($1) }xeg;
    or
    use charnames qw( :full ); $data =~ s{ ([^\w\s\xA0~!@#$%^&*\-_=+()[\]{}|;:'`",<.>/?\N{COPYRIGHT SIGN}\N{SE +CTION SIGN}]) }{ sprintf "{U+%04X}", ord($1) }xeg;

    It seems to me that \w and \s match way more than you want, though.